@crewx/sdk 0.8.2-rc.1 → 0.8.2-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
- 'use strict';var fs$1=require('fs'),X=require('path'),child_process=require('child_process'),jsYaml=require('js-yaml'),zod=require('zod'),module$1=require('module'),ie=require('handlebars'),promises=require('fs/promises'),crypto$1=require('crypto'),events=require('events'),async_hooks=require('async_hooks'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),webStandardStreamableHttp_js=require('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),Hi=require('better-sqlite3'),os$1=require('os'),perf_hooks=require('perf_hooks');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var X__namespace=/*#__PURE__*/_interopNamespace(X);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var Hi__default=/*#__PURE__*/_interopDefault(Hi);var Ot=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var As=Object.getOwnPropertyNames;var Ss=Object.prototype.hasOwnProperty;var U=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var oe=(r,e)=>()=>(r&&(e=r(r=0)),e);var _e=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),zt=(r,e)=>{for(var t in e)Ot(r,t,{get:e[t],enumerable:true});},Is=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of As(e))!Ss.call(r,o)&&o!==t&&Ot(r,o,{get:()=>e[o],enumerable:!(n=Es(e,o))||n.enumerable});return r};var Dr=r=>Is(Ot({},"__esModule",{value:true}),r);var y=oe(()=>{});function gt(r){return typeof r!="string"?void 0:r.trim()||void 0}function mt(r){return gt(r)?.toLowerCase()??""}function Me(r){try{return fs$1.statSync(r).isFile()}catch{return false}}function qr(r,e){if(r.includes("/")||r.includes("\\")||X__namespace.default.isAbsolute(r))return r;let n=(e.PATH??e.Path??process.env.PATH??process.env.Path??"").split(";").map(a=>a.trim()).filter(Boolean),o=X__namespace.default.extname(r).length>0,s=e.PATHEXT??e.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",i=o?[""]:s.split(";").map(a=>a.trim()).filter(Boolean).map(a=>a.startsWith(".")?a:`.${a}`);for(let a of n)for(let l of i){let u=mt(l),c=l.toUpperCase();for(let p of [l,u,c]){let g=X__namespace.default.join(a,`${r}${p}`);if(Me(g))return g}}return r}function Us(r){if(!Me(r))return null;try{let e=fs$1.readFileSync(r,"utf8"),t=[];for(let o of e.matchAll(/"([^"\r\n]*)"/g)){let a=(o[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!a)continue;let l=a.replace(/[\\/]+/g,X__namespace.default.sep).replace(/^[\\/]+/,""),u=X__namespace.default.resolve(X__namespace.default.dirname(r),l);Me(u)&&t.push(u);}return t.find(o=>{let s=mt(X__namespace.default.basename(o));return s!=="node.exe"&&s!=="node"})??null}catch{return null}}function Bs(r,e){if(typeof e=="string")return gt(e)||null;if(!e||typeof e!="object")return null;if(r){let t=e[r],n=typeof t=="string"?gt(t):void 0;if(n)return n}for(let t of Object.values(e)){let n=typeof t=="string"?gt(t):void 0;if(n)return n}return null}function Ws(r,e){if(!e)return null;let t=X__namespace.default.dirname(r),n=[X__namespace.default.resolve(t,"..",e),X__namespace.default.resolve(t,"node_modules",e)];for(let o of n){let s=X__namespace.default.join(o,"package.json");if(Me(s))try{let i=JSON.parse(fs$1.readFileSync(s,"utf8")),a=Bs(e,i.bin);if(!a)continue;let l=X__namespace.default.resolve(o,a);if(Me(l))return l}catch{}}return null}function Js(r){let e=r.platform??process.platform,t=r.env??process.env,n=r.execPath??process.execPath;if(e!=="win32")return {command:r.command,leadingArgv:[],resolution:"direct"};let o=qr(r.command,t),s=mt(X__namespace.default.extname(o));if(s===".js"||s===".cjs"||s===".mjs")return {command:n,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(s===".cmd"||s===".bat"){let i=Us(o)??Ws(o,r.packageName);return i?mt(X__namespace.default.extname(i))===".exe"?{command:i,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:n,leadingArgv:[i],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Vs(r){if(r.candidate.resolution!=="unresolved-wrapper")return {command:r.candidate.command,leadingArgv:r.candidate.leadingArgv,resolution:r.candidate.resolution,windowsHide:r.candidate.windowsHide};if(r.allowShellFallback===true)return {command:r.candidate.command,leadingArgv:[],resolution:"shell-fallback",shell:true};throw new Error(`${X__namespace.default.basename(r.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function je(r){let e=Js(r);return Vs({candidate:e,allowShellFallback:r.allowShellFallback})}function Ne(r,e){return {command:r.command,argv:[...r.leadingArgv,...e],resolution:r.resolution,shell:r.shell,windowsHide:r.windowsHide}}var ft=oe(()=>{y();});function Ks(r){if(r.type!=="usage"||!("input_tokens"in r))return null;let e=Number(r.input_tokens??0),t=Number(r.output_tokens??0),o="cache_read_input_tokens"in r?Number(r.cache_read_input_tokens):void 0,s="cached_input_tokens"in r?Number(r.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:t,cachedInputTokens:i}}function Gs(r){let e=r.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(!("input_tokens"in t))return null;let n=Number(t.input_tokens??0),o=Number(t.output_tokens??0),i="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,a="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,l=i!==void 0?i:a??0;return {inputTokens:i!==void 0?n+i:n,outputTokens:o,cachedInputTokens:l}}function Xs(r){if(r.type!=="step_finish")return null;let t=r.part?.tokens;if(!t)return null;let n=Number(t.input??0),o=Number(t.output??0),s=t.cache,i=s?Number(s.read??0):0;return {inputTokens:n+i,outputTokens:o,cachedInputTokens:i}}function jt(r){if(!r||!r.trim())return;let e=null;for(let t of r.split(`
2
- `))if(t.trim())try{let n=JSON.parse(t),o=Ks(n)??Gs(n)??Xs(n);o&&(e=o);}catch{}return e??void 0}var Nt=oe(()=>{y();});function Qs(r){let e=r.split(`
1
+ 'use strict';var fs$1=require('fs'),X=require('path'),child_process=require('child_process'),jsYaml=require('js-yaml'),zod=require('zod'),module$1=require('module'),ie=require('handlebars'),promises=require('fs/promises'),crypto$1=require('crypto'),events=require('events'),async_hooks=require('async_hooks'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),webStandardStreamableHttp_js=require('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),Ji=require('better-sqlite3'),os=require('os'),perf_hooks=require('perf_hooks');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var X__namespace=/*#__PURE__*/_interopNamespace(X);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var Ji__default=/*#__PURE__*/_interopDefault(Ji);var Ot=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var js=Object.getOwnPropertyNames;var Ns=Object.prototype.hasOwnProperty;var J=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var oe=(r,e)=>()=>(r&&(e=r(r=0)),e);var _e=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),zt=(r,e)=>{for(var t in e)Ot(r,t,{get:e[t],enumerable:true});},Ds=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of js(e))!Ns.call(r,o)&&o!==t&&Ot(r,o,{get:()=>e[o],enumerable:!(n=Ms(e,o))||n.enumerable});return r};var Fr=r=>Ds(Ot({},"__esModule",{value:true}),r);var h=oe(()=>{});function gt(r){return typeof r!="string"?void 0:r.trim()||void 0}function mt(r){return gt(r)?.toLowerCase()??""}function Me(r){try{return fs$1.statSync(r).isFile()}catch{return false}}function Jr(r,e){if(r.includes("/")||r.includes("\\")||X__namespace.default.isAbsolute(r))return r;let n=(e.PATH??e.Path??process.env.PATH??process.env.Path??"").split(";").map(a=>a.trim()).filter(Boolean),o=X__namespace.default.extname(r).length>0,s=e.PATHEXT??e.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",i=o?[""]:s.split(";").map(a=>a.trim()).filter(Boolean).map(a=>a.startsWith(".")?a:`.${a}`);for(let a of n)for(let l of i){let u=mt(l),c=l.toUpperCase();for(let m of [l,u,c]){let p=X__namespace.default.join(a,`${r}${m}`);if(Me(p))return p}}return r}function Ks(r){if(!Me(r))return null;try{let e=fs$1.readFileSync(r,"utf8"),t=[];for(let o of e.matchAll(/"([^"\r\n]*)"/g)){let a=(o[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!a)continue;let l=a.replace(/[\\/]+/g,X__namespace.default.sep).replace(/^[\\/]+/,""),u=X__namespace.default.resolve(X__namespace.default.dirname(r),l);Me(u)&&t.push(u);}return t.find(o=>{let s=mt(X__namespace.default.basename(o));return s!=="node.exe"&&s!=="node"})??null}catch{return null}}function Xs(r,e){if(typeof e=="string")return gt(e)||null;if(!e||typeof e!="object")return null;if(r){let t=e[r],n=typeof t=="string"?gt(t):void 0;if(n)return n}for(let t of Object.values(e)){let n=typeof t=="string"?gt(t):void 0;if(n)return n}return null}function Ys(r,e){if(!e)return null;let t=X__namespace.default.dirname(r),n=[X__namespace.default.resolve(t,"..",e),X__namespace.default.resolve(t,"node_modules",e)];for(let o of n){let s=X__namespace.default.join(o,"package.json");if(Me(s))try{let i=JSON.parse(fs$1.readFileSync(s,"utf8")),a=Xs(e,i.bin);if(!a)continue;let l=X__namespace.default.resolve(o,a);if(Me(l))return l}catch{}}return null}function Qs(r){let e=r.platform??process.platform,t=r.env??process.env,n=r.execPath??process.execPath;if(e!=="win32")return {command:r.command,leadingArgv:[],resolution:"direct"};let o=Jr(r.command,t),s=mt(X__namespace.default.extname(o));if(s===".js"||s===".cjs"||s===".mjs")return {command:n,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(s===".cmd"||s===".bat"){let i=Ks(o)??Ys(o,r.packageName);return i?mt(X__namespace.default.extname(i))===".exe"?{command:i,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:n,leadingArgv:[i],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Zs(r){if(r.candidate.resolution!=="unresolved-wrapper")return {command:r.candidate.command,leadingArgv:r.candidate.leadingArgv,resolution:r.candidate.resolution,windowsHide:r.candidate.windowsHide};if(r.allowShellFallback===true)return {command:r.candidate.command,leadingArgv:[],resolution:"shell-fallback",shell:true};throw new Error(`${X__namespace.default.basename(r.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function je(r){let e=Qs(r);return Zs({candidate:e,allowShellFallback:r.allowShellFallback})}function Ne(r,e){return {command:r.command,argv:[...r.leadingArgv,...e],resolution:r.resolution,shell:r.shell,windowsHide:r.windowsHide}}var ft=oe(()=>{h();});function ei(r){if(r.type!=="usage"||!("input_tokens"in r))return null;let e=Number(r.input_tokens??0),t=Number(r.output_tokens??0),o="cache_read_input_tokens"in r?Number(r.cache_read_input_tokens):void 0,s="cached_input_tokens"in r?Number(r.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:t,cachedInputTokens:i}}function ti(r){let e=r.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(!("input_tokens"in t))return null;let n=Number(t.input_tokens??0),o=Number(t.output_tokens??0),i="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,a="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,l=i!==void 0?i:a??0;return {inputTokens:i!==void 0?n+i:n,outputTokens:o,cachedInputTokens:l}}function ri(r){if(r.type!=="step_finish")return null;let t=r.part?.tokens;if(!t)return null;let n=Number(t.input??0),o=Number(t.output??0),s=t.cache,i=s?Number(s.read??0):0;return {inputTokens:n+i,outputTokens:o,cachedInputTokens:i}}function jt(r){if(!r||!r.trim())return;let e=null;for(let t of r.split(`
2
+ `))if(t.trim())try{let n=JSON.parse(t),o=ei(n)??ti(n)??ri(n);o&&(e=o);}catch{}return e??void 0}var Nt=oe(()=>{h();});function oi(r){let e=r.split(`
3
3
  `).filter(l=>l.trim()),t=[],n=[],o=[],s=[],i=[],a=null;for(let l of e)try{let u=JSON.parse(l);if(u.type==="assistant"&&Array.isArray(u.message?.content))for(let c of u.message.content)c.type==="text"&&typeof c.text=="string"&&c.text.trim()&&t.push(c.text.trim());if(u.type==="message"&&u.role==="assistant"&&u.delta===!0&&typeof u.content=="string"&&n.push(u.content),u.type==="assistant.message"&&typeof u.data?.content=="string"){let c=u.data.content;c.trim()&&o.push(c.trim());}if(u.type==="item.completed"&&(u.item?.type==="message"||u.item?.type==="agent_message")&&typeof u.item?.text=="string"){let c=u.item.text;c.trim()&&s.push(c.trim());}if(u.type==="text"&&typeof u.part?.text=="string"){let c=u.part.text;c.trim()&&i.push(c.trim());}u.type==="result"&&typeof u.result=="string"&&(a=u.result);}catch{}return t.length>0?t.join(`
4
4
 
5
5
  `):n.length>0?n.join(""):o.length>0?o.join(`
6
6
 
7
7
  `):s.length>0?s.join(`
8
8
 
9
- `):i.length>0?i.join(""):a||r.trim()}function Zs(r){let e=jt(r);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function Ie(r,e){Ur.set(r,e);}function pe(r){let e=r.split("/");if(e.length!==2)throw new exports.ProviderError(`Invalid provider format: "${r}". Expected namespace/id (e.g., cli/claude)`,r);let[t,n]=e,o=Ur.get(t);if(o)return o(n,r);if(t==="cli"){let s=Fr[n];if(!s)throw new exports.ProviderError(`Unknown CLI provider id: "${n}". Supported: ${Object.keys(Fr).join(", ")}`,r);return new $t(n,s,r)}throw new exports.ProviderError(`Unsupported provider namespace: "${t}". Register a factory with registerProviderFactory('${t}', factory).`,r)}exports.ProviderError=void 0;exports.ClientToolCallRequiredError=void 0;var Ur,Fr,$t,Re=oe(()=>{y();ft();Nt();exports.ProviderError=class extends Error{constructor(t,n){super(t);this.providerStr=n;this.name="ProviderError";}providerStr},exports.ClientToolCallRequiredError=class extends Error{constructor(t,n){super(`Client tool call required: ${t.toolName}`);this.toolCall=t;this.continuationState=n;}toolCall;continuationState;name="ClientToolCallRequiredError"},Ur=new Map;Fr={claude:"claude",gemini:"gemini",copilot:"copilot",codex:"codex",opencode:"opencode"};$t=class{constructor(e,t,n){this.providerId=e;this.cliCommand=t;this.providerStr=n;}providerId;cliCommand;providerStr;async execute(e,t){let{args:n,stdinMessage:o}=this.buildArgs(e,t,true);return t?.onCommand?.(`${this.cliCommand} ${n.join(" ")}`),this.runProcess(n,t,o)}async query(e,t){let{args:n,stdinMessage:o}=this.buildArgs(e,t);return t?.onCommand?.(`${this.cliCommand} ${n.join(" ")}`),this.runProcess(n,t,o)}runProcess(e,t,n){return new Promise((o,s)=>{let i=je({command:this.cliCommand,allowShellFallback:true}),a=Ne(i,e),l=child_process.spawn(a.command,a.argv,{env:{...process.env,...t?.env??{}},cwd:t?.cwd,stdio:["pipe","pipe","pipe"],shell:a.shell??false,windowsHide:a.windowsHide});n!==void 0&&l.stdin.write(n),l.stdin.end(),l.pid!==void 0&&t?.onPid?.(l.pid);let u="",c="",p="",g="";l.stdout.on("data",m=>{let v=m.toString();u+=v,p+=v;let f=p.split(`
10
- `);p=f.pop()??"";for(let d of f)d.trim()&&t?.onOutput?.(d,"stdout");}),l.stderr.on("data",m=>{let v=m.toString();c+=v,g+=v;let f=g.split(`
11
- `);g=f.pop()??"";for(let d of f)d.trim()&&t?.onOutput?.(d,"stderr");}),l.on("error",m=>{m.code==="ENOENT"?s(new exports.ProviderError(`CLI command "${this.cliCommand}" not found. Is ${this.providerStr} installed?`,this.providerStr)):s(new exports.ProviderError(`Spawn error: ${m.message}`,this.providerStr));}),l.on("close",m=>{p.trim()&&t?.onOutput?.(p,"stdout"),g.trim()&&t?.onOutput?.(g,"stderr");let v=m??0;if(t?.onExitCode?.(v),m!==0){s(new exports.ProviderError(`Process exited with code ${m}: ${c.slice(0,500)}`,this.providerStr));return}let{usage:f,model:d}=this.parseResultEvent(u);f&&t?.onUsage&&t.onUsage(f);let h=d??(this.providerId==="opencode"?t?.model??null:null);h&&t?.onModel&&t.onModel(h);let _=this.parseOutput(u);o(_);});})}buildArgs(e,t,n=false){let o=t?.systemPrompt?`${t.systemPrompt}
9
+ `):i.length>0?i.join(""):a||r.trim()}function si(r){let e=jt(r);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function ii(r,e,t,n,o,s){return new Promise((i,a)=>{let l=o?.timeoutMs??72e5,u=o?.idleTimeoutMs??600*1e3,c=o?.killGraceMs??2e3,m=je({command:r,allowShellFallback:true}),p=Ne(m,e),g=child_process.spawn(p.command,p.argv,{env:{...process.env,...o?.env??{}},cwd:o?.cwd,stdio:["pipe","pipe","pipe"],shell:p.shell??false,windowsHide:p.windowsHide});s!==void 0&&g.stdin.write(s),g.stdin.end(),g.pid!==void 0&&o?.onPid?.(g.pid);let v=false,f=null,d=()=>{try{g.kill("SIGKILL");}catch{}},y=T=>{if(!v){f=T;try{g.kill("SIGTERM");}catch{}setTimeout(d,c).unref();}},b=setTimeout(()=>y("idle"),u),k=setTimeout(()=>y("total"),l);b.unref(),k.unref();let w=()=>b.refresh(),x="",S="",z="",R="";g.stdout.on("data",T=>{let O=T.toString();w(),x+=O,z+=O;let j=z.split(`
10
+ `);z=j.pop()??"";for(let I of j)I.trim()&&o?.onOutput?.(I,"stdout");}),g.stderr.on("data",T=>{let O=T.toString();w(),S+=O,R+=O;let j=R.split(`
11
+ `);R=j.pop()??"";for(let I of j)I.trim()&&o?.onOutput?.(I,"stderr");}),g.on("error",T=>{v=true,clearTimeout(b),clearTimeout(k),T.code==="ENOENT"?a(new exports.ProviderError(`CLI command "${r}" not found. Is ${t} installed?`,t)):a(new exports.ProviderError(`Spawn error: ${T.message}`,t));}),g.on("close",T=>{v=true,clearTimeout(b),clearTimeout(k),z.trim()&&o?.onOutput?.(z,"stdout"),R.trim()&&o?.onOutput?.(R,"stderr");let O=T??0;if(o?.onExitCode?.(O),f==="idle"&&T!==0)return a(new Dt(`No output for ${u}ms; process killed.`,t));if(f==="total"&&T!==0)return a(new $t(`Total runtime exceeded ${l}ms; process killed.`,t));if(T!==0){a(new exports.ProviderError(`Process exited with code ${T}: ${S.slice(0,500)}`,t));return}let j=oi(x);i({stdout:x,parsed:j});});})}function Ie(r,e){Gr.set(r,e);}function pe(r){let e=r.split("/");if(e.length!==2)throw new exports.ProviderError(`Invalid provider format: "${r}". Expected namespace/id (e.g., cli/claude)`,r);let[t,n]=e,o=Gr.get(t);if(o)return o(n,r);if(t==="cli"){let s=Vr[n];if(!s)throw new exports.ProviderError(`Unknown CLI provider id: "${n}". Supported: ${Object.keys(Vr).join(", ")}`,r);return new Ht(n,s,r)}throw new exports.ProviderError(`Unsupported provider namespace: "${t}". Register a factory with registerProviderFactory('${t}', factory).`,r)}exports.ProviderError=void 0;var Dt,$t;exports.ClientToolCallRequiredError=void 0;var Gr,Vr,Ht,Re=oe(()=>{h();ft();Nt();exports.ProviderError=class extends Error{constructor(t,n){super(t);this.providerStr=n;this.name="ProviderError";}providerStr},Dt=class extends exports.ProviderError{constructor(e,t){super(e,t),this.name="IdleTimeoutError";}},$t=class extends exports.ProviderError{constructor(e,t){super(e,t),this.name="TotalTimeoutError";}};exports.ClientToolCallRequiredError=class extends Error{constructor(t,n){super(`Client tool call required: ${t.toolName}`);this.toolCall=t;this.continuationState=n;}toolCall;continuationState;name="ClientToolCallRequiredError"},Gr=new Map;Vr={claude:"claude",gemini:"gemini",copilot:"copilot",codex:"codex",opencode:"opencode"};Ht=class{constructor(e,t,n){this.providerId=e;this.cliCommand=t;this.providerStr=n;}providerId;cliCommand;providerStr;async execute(e,t){let{args:n,stdinMessage:o}=this.buildArgs(e,t,true);t?.onCommand?.(`${this.cliCommand} ${n.join(" ")}`);let{stdout:s,parsed:i}=await this.runProcess(n,t,o);return this.handleResultMeta(s,t),i}async query(e,t){let{args:n,stdinMessage:o}=this.buildArgs(e,t);t?.onCommand?.(`${this.cliCommand} ${n.join(" ")}`);let{stdout:s,parsed:i}=await this.runProcess(n,t,o);return this.handleResultMeta(s,t),i}runProcess(e,t,n){return ii(this.cliCommand,e,this.providerStr,this.providerId,t,n)}handleResultMeta(e,t){let{usage:n,model:o}=this.parseResultEvent(e);n&&t?.onUsage&&t.onUsage(n);let s=o??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}buildArgs(e,t,n=false){let o=t?.systemPrompt?`${t.systemPrompt}
12
12
 
13
13
  ---
14
14
 
15
- ${e}`:e;if(this.providerId==="copilot"){let i=t?.additionalArgs?[...t.additionalArgs]:[];return t?.model&&i.push("--model",t.model),{args:i,stdinMessage:o}}if(this.providerId==="opencode"){let i=t?.additionalArgs,a=i!==void 0?[...i]:["run"];return a.includes("--format")||a.push("--format","json"),t?.model&&a.push("--model",t.model),a.push(o),{args:a}}if(t?.additionalArgs!==void 0){let i=[...t.additionalArgs],a=i.indexOf("-p");return a!==-1?(i.splice(a+1,0,o),t.model&&i.push("--model",t.model),{args:i}):(this.providerId==="codex"&&!i.includes("--json")&&!i.includes("--experimental-json")&&i.push("--json"),t.model&&i.push("--model",t.model),{args:i,stdinMessage:o})}let s=["-p",o,"--output-format","stream-json","--verbose"];return n&&s.push("--dangerously-skip-permissions"),t?.model&&s.push("--model",t.model),{args:s}}parseOutput(e){return Qs(e)}parseResultEvent(e){let t=Zs(e),n=e.split(`
16
- `);for(let o of n)if(o.trim())try{let s=JSON.parse(o);if(s.type==="result"){let i=s.usage,a=i?{inputTokens:Number(i.input_tokens??0),outputTokens:Number(i.output_tokens??0),cachedInputTokens:Number(i.cache_read_input_tokens??0),costUsd:Number(s.total_cost_usd??0)}:t,l=s.modelUsage,u=l?Object.keys(l)[0]??null:null;return {usage:a,model:u}}}catch{}return {usage:t,model:null}}};});var L=_e((vm,Zn)=>{y();var rr=Object.defineProperty,Vi=Object.getOwnPropertyDescriptor,Ki=Object.getOwnPropertyNames,Gi=Object.prototype.hasOwnProperty,Xi=(r,e)=>{for(var t in e)rr(r,t,{get:e[t],enumerable:true});},Yi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ki(e))!Gi.call(r,o)&&o!==t&&rr(r,o,{get:()=>e[o],enumerable:!(n=Vi(e,o))||n.enumerable});return r},Qi=r=>Yi(rr({},"__esModule",{value:true}),r),cn={};Xi(cn,{AISDKError:()=>D,APICallError:()=>ra,EmptyResponseBodyError:()=>oa,InvalidArgumentError:()=>ia,InvalidPromptError:()=>la,InvalidResponseDataError:()=>ca,JSONParseError:()=>pa,LoadAPIKeyError:()=>ma,LoadSettingError:()=>ha,NoContentGeneratedError:()=>va,NoSuchModelError:()=>ba,TooManyEmbeddingValuesForCallError:()=>xa,TypeValidationError:()=>Ca,UnsupportedFunctionalityError:()=>Pa,getErrorMessage:()=>nr,isJSONArray:()=>Ea,isJSONObject:()=>Aa,isJSONValue:()=>Je});Zn.exports=Qi(cn);var dn="vercel.ai.error",Zi=Symbol.for(dn),pn,ea=class gn extends Error{constructor({name:e,message:t,cause:n}){super(t),this[pn]=true,this.name=e,this.cause=n;}static isInstance(e){return gn.hasMarker(e,dn)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===true}};pn=Zi;var D=ea,mn="AI_APICallError",fn=`vercel.ai.error.${mn}`,ta=Symbol.for(fn),hn,ra=class extends D{constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:s,cause:i,isRetryable:a=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:mn,message:r,cause:i}),this[hn]=true,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=a,this.data=l;}static isInstance(r){return D.hasMarker(r,fn)}};hn=ta;var yn="AI_EmptyResponseBodyError",vn=`vercel.ai.error.${yn}`,na=Symbol.for(vn),wn,oa=class extends D{constructor({message:r="Empty response body"}={}){super({name:yn,message:r}),this[wn]=true;}static isInstance(r){return D.hasMarker(r,vn)}};wn=na;function nr(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var bn="AI_InvalidArgumentError",_n=`vercel.ai.error.${bn}`,sa=Symbol.for(_n),xn,ia=class extends D{constructor({message:r,cause:e,argument:t}){super({name:bn,message:r,cause:e}),this[xn]=true,this.argument=t;}static isInstance(r){return D.hasMarker(r,_n)}};xn=sa;var kn="AI_InvalidPromptError",Rn=`vercel.ai.error.${kn}`,aa=Symbol.for(Rn),Cn,la=class extends D{constructor({prompt:r,message:e,cause:t}){super({name:kn,message:`Invalid prompt: ${e}`,cause:t}),this[Cn]=true,this.prompt=r;}static isInstance(r){return D.hasMarker(r,Rn)}};Cn=aa;var Tn="AI_InvalidResponseDataError",Pn=`vercel.ai.error.${Tn}`,ua=Symbol.for(Pn),En,ca=class extends D{constructor({data:r,message:e=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Tn,message:e}),this[En]=true,this.data=r;}static isInstance(r){return D.hasMarker(r,Pn)}};En=ua;var An="AI_JSONParseError",Sn=`vercel.ai.error.${An}`,da=Symbol.for(Sn),In,pa=class extends D{constructor({text:r,cause:e}){super({name:An,message:`JSON parsing failed: Text: ${r}.
17
- Error message: ${nr(e)}`,cause:e}),this[In]=true,this.text=r;}static isInstance(r){return D.hasMarker(r,Sn)}};In=da;var On="AI_LoadAPIKeyError",zn=`vercel.ai.error.${On}`,ga=Symbol.for(zn),Mn,ma=class extends D{constructor({message:r}){super({name:On,message:r}),this[Mn]=true;}static isInstance(r){return D.hasMarker(r,zn)}};Mn=ga;var jn="AI_LoadSettingError",Nn=`vercel.ai.error.${jn}`,fa=Symbol.for(Nn),$n,ha=class extends D{constructor({message:r}){super({name:jn,message:r}),this[$n]=true;}static isInstance(r){return D.hasMarker(r,Nn)}};$n=fa;var Dn="AI_NoContentGeneratedError",Hn=`vercel.ai.error.${Dn}`,ya=Symbol.for(Hn),Ln,va=class extends D{constructor({message:r="No content generated."}={}){super({name:Dn,message:r}),this[Ln]=true;}static isInstance(r){return D.hasMarker(r,Hn)}};Ln=ya;var qn="AI_NoSuchModelError",Fn=`vercel.ai.error.${qn}`,wa=Symbol.for(Fn),Un,ba=class extends D{constructor({errorName:r=qn,modelId:e,modelType:t,message:n=`No such ${t}: ${e}`}){super({name:r,message:n}),this[Un]=true,this.modelId=e,this.modelType=t;}static isInstance(r){return D.hasMarker(r,Fn)}};Un=wa;var Bn="AI_TooManyEmbeddingValuesForCallError",Wn=`vercel.ai.error.${Bn}`,_a=Symbol.for(Wn),Jn,xa=class extends D{constructor(r){super({name:Bn,message:`Too many values for a single embedding call. The ${r.provider} model "${r.modelId}" can only embed up to ${r.maxEmbeddingsPerCall} values per call, but ${r.values.length} values were provided.`}),this[Jn]=true,this.provider=r.provider,this.modelId=r.modelId,this.maxEmbeddingsPerCall=r.maxEmbeddingsPerCall,this.values=r.values;}static isInstance(r){return D.hasMarker(r,Wn)}};Jn=_a;var Vn="AI_TypeValidationError",Kn=`vercel.ai.error.${Vn}`,ka=Symbol.for(Kn),Gn,Ra=class tr extends D{constructor({value:e,cause:t}){super({name:Vn,message:`Type validation failed: Value: ${JSON.stringify(e)}.
18
- Error message: ${nr(t)}`,cause:t}),this[Gn]=true,this.value=e;}static isInstance(e){return D.hasMarker(e,Kn)}static wrap({value:e,cause:t}){return tr.isInstance(t)&&t.value===e?t:new tr({value:e,cause:t})}};Gn=ka;var Ca=Ra,Xn="AI_UnsupportedFunctionalityError",Yn=`vercel.ai.error.${Xn}`,Ta=Symbol.for(Yn),Qn,Pa=class extends D{constructor({functionality:r,message:e=`'${r}' functionality not supported.`}){super({name:Xn,message:e}),this[Qn]=true,this.functionality=r;}static isInstance(r){return D.hasMarker(r,Yn)}};Qn=Ta;function Je(r){return r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?true:Array.isArray(r)?r.every(Je):typeof r=="object"?Object.entries(r).every(([e,t])=>typeof e=="string"&&Je(t)):false}function Ea(r){return Array.isArray(r)&&r.every(Je)}function Aa(r){return r!=null&&typeof r=="object"&&Object.entries(r).every(([e,t])=>typeof e=="string"&&Je(t))}});var to=_e((Om,eo)=>{y();var Sa="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Ia=(r,e=21)=>(t=e)=>{let n="",o=t|0;for(;o--;)n+=r[Math.random()*r.length|0];return n},Oa=(r=21)=>{let e="",t=r|0;for(;t--;)e+=Sa[Math.random()*64|0];return e};eo.exports={nanoid:Oa,customAlphabet:Ia};});var io=_e((Mm,Oe)=>{y();var za=typeof Buffer<"u",ro=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,no=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function oo(r,e,t){t==null&&e!==null&&typeof e=="object"&&(t=e,e=void 0),za&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let n=JSON.parse(r,e);if(n===null||typeof n!="object")return n;let o=t&&t.protoAction||"error",s=t&&t.constructorAction||"error";if(o==="ignore"&&s==="ignore")return n;if(o!=="ignore"&&s!=="ignore"){if(ro.test(r)===false&&no.test(r)===false)return n}else if(o!=="ignore"&&s==="ignore"){if(ro.test(r)===false)return n}else if(no.test(r)===false)return n;return so(n,{protoAction:o,constructorAction:s,safe:t&&t.safe})}function so(r,{protoAction:e="error",constructorAction:t="error",safe:n}={}){let o=[r];for(;o.length;){let s=o;o=[];for(let i of s){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(i,"__proto__")){if(n===true)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete i.__proto__;}if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype")){if(n===true)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete i.constructor;}for(let a in i){let l=i[a];l&&typeof l=="object"&&o.push(l);}}}return r}function or(r,e,t){let n=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return oo(r,e,t)}finally{Error.stackTraceLimit=n;}}function Ma(r,e){let t=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return oo(r,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=t;}}Oe.exports=or;Oe.exports.default=or;Oe.exports.parse=or;Oe.exports.safeParse=Ma;Oe.exports.scan=so;});var V=_e((Nm,vo)=>{y();var ja=Object.create,bt=Object.defineProperty,Na=Object.getOwnPropertyDescriptor,$a=Object.getOwnPropertyNames,Da=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty,La=(r,e)=>{for(var t in e)bt(r,t,{get:e[t],enumerable:true});},ao=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $a(e))!Ha.call(r,o)&&o!==t&&bt(r,o,{get:()=>e[o],enumerable:!(n=Na(e,o))||n.enumerable});return r},qa=(r,e,t)=>(t=r!=null?ja(Da(r)):{},ao(!r||!r.__esModule?bt(t,"default",{value:r,enumerable:true}):t,r)),Fa=r=>ao(bt({},"__esModule",{value:true}),r),lo={};La(lo,{asValidator:()=>mo,combineHeaders:()=>Ua,convertAsyncIteratorToReadableStream:()=>Ba,convertBase64ToUint8Array:()=>yl,convertUint8ArrayToBase64:()=>vl,createBinaryResponseHandler:()=>gl,createEventSourceParserStream:()=>uo,createEventSourceResponseHandler:()=>cl,createIdGenerator:()=>co,createJsonErrorResponseHandler:()=>ul,createJsonResponseHandler:()=>pl,createJsonStreamResponseHandler:()=>dl,createStatusCodeErrorResponseHandler:()=>ml,delay:()=>Wa,extractResponseHeaders:()=>fe,generateId:()=>Ga,getErrorMessage:()=>Xa,getFromApi:()=>Qa,isAbortError:()=>Pe,isParsableJson:()=>rl,isValidator:()=>go,loadApiKey:()=>Za,loadOptionalSetting:()=>el,loadSetting:()=>tl,parseJSON:()=>yo,parseProviderOptions:()=>ol,postFormDataToApi:()=>al,postJsonToApi:()=>il,postToApi:()=>lr,removeUndefinedEntries:()=>ir,resolve:()=>ll,safeParseJSON:()=>xt,safeValidateTypes:()=>_t,validateTypes:()=>ho,validator:()=>po,validatorSymbol:()=>wt,withoutTrailingSlash:()=>wl,zodValidator:()=>fo});vo.exports=Fa(lo);function Ua(...r){return r.reduce((e,t)=>({...e,...t??{}}),{})}function Ba(r){return new ReadableStream({async pull(e){try{let{value:t,done:n}=await r.next();n?e.close():e.enqueue(t);}catch(t){e.error(t);}},cancel(){}})}async function Wa(r){return r==null?Promise.resolve():new Promise(e=>setTimeout(e,r))}function uo(){let r="",e,t=[],n,o;function s(l,u){if(l===""){i(u);return}if(l.startsWith(":"))return;let c=l.indexOf(":");if(c===-1){a(l,"");return}let p=l.slice(0,c),g=c+1,m=g<l.length&&l[g]===" "?l.slice(g+1):l.slice(g);a(p,m);}function i(l){t.length>0&&(l.enqueue({event:e,data:t.join(`
19
- `),id:n,retry:o}),t=[],e=void 0,o=void 0);}function a(l,u){switch(l){case "event":e=u;break;case "data":t.push(u);break;case "id":n=u;break;case "retry":let c=parseInt(u,10);isNaN(c)||(o=c);break}}return new TransformStream({transform(l,u){let{lines:c,incompleteLine:p}=Ja(r,l);r=p;for(let g=0;g<c.length;g++)s(c[g],u);},flush(l){s(r,l),i(l);}})}function Ja(r,e){let t=[],n=r;for(let o=0;o<e.length;){let s=e[o++];s===`
15
+ ${e}`:e;if(this.providerId==="copilot"){let i=t?.additionalArgs?[...t.additionalArgs]:[];return t?.model&&i.push("--model",t.model),{args:i,stdinMessage:o}}if(this.providerId==="opencode"){let i=t?.additionalArgs,a=i!==void 0?[...i]:["run"];return a.includes("--format")||a.push("--format","json"),t?.model&&a.push("--model",t.model),a.push(o),{args:a}}if(t?.additionalArgs!==void 0){let i=[...t.additionalArgs],a=i.indexOf("-p");return a!==-1?(i.splice(a+1,0,o),t.model&&i.push("--model",t.model),{args:i}):(this.providerId==="codex"&&!i.includes("--json")&&!i.includes("--experimental-json")&&i.push("--json"),t.model&&i.push("--model",t.model),{args:i,stdinMessage:o})}let s=["-p",o,"--output-format","stream-json","--verbose"];return n&&s.push("--dangerously-skip-permissions"),t?.model&&s.push("--model",t.model),{args:s}}parseResultEvent(e){let t=si(e),n=e.split(`
16
+ `);for(let o of n)if(o.trim())try{let s=JSON.parse(o);if(s.type==="result"){let i=s.usage,a=i?{inputTokens:Number(i.input_tokens??0),outputTokens:Number(i.output_tokens??0),cachedInputTokens:Number(i.cache_read_input_tokens??0),costUsd:Number(s.total_cost_usd??0)}:t,l=s.modelUsage,u=l?Object.keys(l)[0]??null:null;return {usage:a,model:u}}}catch{}return {usage:t,model:null}}};});var q=_e((Em,so)=>{h();var ir=Object.defineProperty,ea=Object.getOwnPropertyDescriptor,ta=Object.getOwnPropertyNames,ra=Object.prototype.hasOwnProperty,na=(r,e)=>{for(var t in e)ir(r,t,{get:e[t],enumerable:true});},oa=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ta(e))!ra.call(r,o)&&o!==t&&ir(r,o,{get:()=>e[o],enumerable:!(n=ea(e,o))||n.enumerable});return r},sa=r=>oa(ir({},"__esModule",{value:true}),r),hn={};na(hn,{AISDKError:()=>H,APICallError:()=>ua,EmptyResponseBodyError:()=>da,InvalidArgumentError:()=>ga,InvalidPromptError:()=>fa,InvalidResponseDataError:()=>ya,JSONParseError:()=>wa,LoadAPIKeyError:()=>_a,LoadSettingError:()=>ka,NoContentGeneratedError:()=>Ca,NoSuchModelError:()=>Pa,TooManyEmbeddingValuesForCallError:()=>Aa,TypeValidationError:()=>Oa,UnsupportedFunctionalityError:()=>Ma,getErrorMessage:()=>ar,isJSONArray:()=>ja,isJSONObject:()=>Na,isJSONValue:()=>Je});so.exports=sa(hn);var yn="vercel.ai.error",ia=Symbol.for(yn),vn,aa=class wn extends Error{constructor({name:e,message:t,cause:n}){super(t),this[vn]=true,this.name=e,this.cause=n;}static isInstance(e){return wn.hasMarker(e,yn)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===true}};vn=ia;var H=aa,bn="AI_APICallError",_n=`vercel.ai.error.${bn}`,la=Symbol.for(_n),xn,ua=class extends H{constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:s,cause:i,isRetryable:a=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:bn,message:r,cause:i}),this[xn]=true,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=a,this.data=l;}static isInstance(r){return H.hasMarker(r,_n)}};xn=la;var kn="AI_EmptyResponseBodyError",Rn=`vercel.ai.error.${kn}`,ca=Symbol.for(Rn),Cn,da=class extends H{constructor({message:r="Empty response body"}={}){super({name:kn,message:r}),this[Cn]=true;}static isInstance(r){return H.hasMarker(r,Rn)}};Cn=ca;function ar(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var Tn="AI_InvalidArgumentError",Pn=`vercel.ai.error.${Tn}`,pa=Symbol.for(Pn),En,ga=class extends H{constructor({message:r,cause:e,argument:t}){super({name:Tn,message:r,cause:e}),this[En]=true,this.argument=t;}static isInstance(r){return H.hasMarker(r,Pn)}};En=pa;var An="AI_InvalidPromptError",Sn=`vercel.ai.error.${An}`,ma=Symbol.for(Sn),In,fa=class extends H{constructor({prompt:r,message:e,cause:t}){super({name:An,message:`Invalid prompt: ${e}`,cause:t}),this[In]=true,this.prompt=r;}static isInstance(r){return H.hasMarker(r,Sn)}};In=ma;var On="AI_InvalidResponseDataError",zn=`vercel.ai.error.${On}`,ha=Symbol.for(zn),Mn,ya=class extends H{constructor({data:r,message:e=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:On,message:e}),this[Mn]=true,this.data=r;}static isInstance(r){return H.hasMarker(r,zn)}};Mn=ha;var jn="AI_JSONParseError",Nn=`vercel.ai.error.${jn}`,va=Symbol.for(Nn),Dn,wa=class extends H{constructor({text:r,cause:e}){super({name:jn,message:`JSON parsing failed: Text: ${r}.
17
+ Error message: ${ar(e)}`,cause:e}),this[Dn]=true,this.text=r;}static isInstance(r){return H.hasMarker(r,Nn)}};Dn=va;var $n="AI_LoadAPIKeyError",Hn=`vercel.ai.error.${$n}`,ba=Symbol.for(Hn),Ln,_a=class extends H{constructor({message:r}){super({name:$n,message:r}),this[Ln]=true;}static isInstance(r){return H.hasMarker(r,Hn)}};Ln=ba;var qn="AI_LoadSettingError",Fn=`vercel.ai.error.${qn}`,xa=Symbol.for(Fn),Un,ka=class extends H{constructor({message:r}){super({name:qn,message:r}),this[Un]=true;}static isInstance(r){return H.hasMarker(r,Fn)}};Un=xa;var Bn="AI_NoContentGeneratedError",Wn=`vercel.ai.error.${Bn}`,Ra=Symbol.for(Wn),Jn,Ca=class extends H{constructor({message:r="No content generated."}={}){super({name:Bn,message:r}),this[Jn]=true;}static isInstance(r){return H.hasMarker(r,Wn)}};Jn=Ra;var Vn="AI_NoSuchModelError",Gn=`vercel.ai.error.${Vn}`,Ta=Symbol.for(Gn),Kn,Pa=class extends H{constructor({errorName:r=Vn,modelId:e,modelType:t,message:n=`No such ${t}: ${e}`}){super({name:r,message:n}),this[Kn]=true,this.modelId=e,this.modelType=t;}static isInstance(r){return H.hasMarker(r,Gn)}};Kn=Ta;var Xn="AI_TooManyEmbeddingValuesForCallError",Yn=`vercel.ai.error.${Xn}`,Ea=Symbol.for(Yn),Qn,Aa=class extends H{constructor(r){super({name:Xn,message:`Too many values for a single embedding call. The ${r.provider} model "${r.modelId}" can only embed up to ${r.maxEmbeddingsPerCall} values per call, but ${r.values.length} values were provided.`}),this[Qn]=true,this.provider=r.provider,this.modelId=r.modelId,this.maxEmbeddingsPerCall=r.maxEmbeddingsPerCall,this.values=r.values;}static isInstance(r){return H.hasMarker(r,Yn)}};Qn=Ea;var Zn="AI_TypeValidationError",eo=`vercel.ai.error.${Zn}`,Sa=Symbol.for(eo),to,Ia=class sr extends H{constructor({value:e,cause:t}){super({name:Zn,message:`Type validation failed: Value: ${JSON.stringify(e)}.
18
+ Error message: ${ar(t)}`,cause:t}),this[to]=true,this.value=e;}static isInstance(e){return H.hasMarker(e,eo)}static wrap({value:e,cause:t}){return sr.isInstance(t)&&t.value===e?t:new sr({value:e,cause:t})}};to=Sa;var Oa=Ia,ro="AI_UnsupportedFunctionalityError",no=`vercel.ai.error.${ro}`,za=Symbol.for(no),oo,Ma=class extends H{constructor({functionality:r,message:e=`'${r}' functionality not supported.`}){super({name:ro,message:e}),this[oo]=true,this.functionality=r;}static isInstance(r){return H.hasMarker(r,no)}};oo=za;function Je(r){return r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?true:Array.isArray(r)?r.every(Je):typeof r=="object"?Object.entries(r).every(([e,t])=>typeof e=="string"&&Je(t)):false}function ja(r){return Array.isArray(r)&&r.every(Je)}function Na(r){return r!=null&&typeof r=="object"&&Object.entries(r).every(([e,t])=>typeof e=="string"&&Je(t))}});var ao=_e((Fm,io)=>{h();var Da="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",$a=(r,e=21)=>(t=e)=>{let n="",o=t|0;for(;o--;)n+=r[Math.random()*r.length|0];return n},Ha=(r=21)=>{let e="",t=r|0;for(;t--;)e+=Da[Math.random()*64|0];return e};io.exports={nanoid:Ha,customAlphabet:$a};});var go=_e((Bm,Oe)=>{h();var La=typeof Buffer<"u",lo=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,uo=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function co(r,e,t){t==null&&e!==null&&typeof e=="object"&&(t=e,e=void 0),La&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let n=JSON.parse(r,e);if(n===null||typeof n!="object")return n;let o=t&&t.protoAction||"error",s=t&&t.constructorAction||"error";if(o==="ignore"&&s==="ignore")return n;if(o!=="ignore"&&s!=="ignore"){if(lo.test(r)===false&&uo.test(r)===false)return n}else if(o!=="ignore"&&s==="ignore"){if(lo.test(r)===false)return n}else if(uo.test(r)===false)return n;return po(n,{protoAction:o,constructorAction:s,safe:t&&t.safe})}function po(r,{protoAction:e="error",constructorAction:t="error",safe:n}={}){let o=[r];for(;o.length;){let s=o;o=[];for(let i of s){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(i,"__proto__")){if(n===true)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete i.__proto__;}if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype")){if(n===true)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete i.constructor;}for(let a in i){let l=i[a];l&&typeof l=="object"&&o.push(l);}}}return r}function lr(r,e,t){let n=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return co(r,e,t)}finally{Error.stackTraceLimit=n;}}function qa(r,e){let t=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return co(r,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=t;}}Oe.exports=lr;Oe.exports.default=lr;Oe.exports.parse=lr;Oe.exports.safeParse=qa;Oe.exports.scan=po;});var G=_e((Jm,Ro)=>{h();var Fa=Object.create,bt=Object.defineProperty,Ua=Object.getOwnPropertyDescriptor,Ba=Object.getOwnPropertyNames,Wa=Object.getPrototypeOf,Ja=Object.prototype.hasOwnProperty,Va=(r,e)=>{for(var t in e)bt(r,t,{get:e[t],enumerable:true});},mo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ba(e))!Ja.call(r,o)&&o!==t&&bt(r,o,{get:()=>e[o],enumerable:!(n=Ua(e,o))||n.enumerable});return r},Ga=(r,e,t)=>(t=r!=null?Fa(Wa(r)):{},mo(!r||!r.__esModule?bt(t,"default",{value:r,enumerable:true}):t,r)),Ka=r=>mo(bt({},"__esModule",{value:true}),r),fo={};Va(fo,{asValidator:()=>bo,combineHeaders:()=>Xa,convertAsyncIteratorToReadableStream:()=>Ya,convertBase64ToUint8Array:()=>Rl,convertUint8ArrayToBase64:()=>Cl,createBinaryResponseHandler:()=>bl,createEventSourceParserStream:()=>ho,createEventSourceResponseHandler:()=>yl,createIdGenerator:()=>yo,createJsonErrorResponseHandler:()=>hl,createJsonResponseHandler:()=>wl,createJsonStreamResponseHandler:()=>vl,createStatusCodeErrorResponseHandler:()=>_l,delay:()=>Qa,extractResponseHeaders:()=>fe,generateId:()=>rl,getErrorMessage:()=>nl,getFromApi:()=>sl,isAbortError:()=>Pe,isParsableJson:()=>ul,isValidator:()=>wo,loadApiKey:()=>il,loadOptionalSetting:()=>al,loadSetting:()=>ll,parseJSON:()=>ko,parseProviderOptions:()=>dl,postFormDataToApi:()=>ml,postJsonToApi:()=>gl,postToApi:()=>pr,removeUndefinedEntries:()=>cr,resolve:()=>fl,safeParseJSON:()=>xt,safeValidateTypes:()=>_t,validateTypes:()=>xo,validator:()=>vo,validatorSymbol:()=>wt,withoutTrailingSlash:()=>Tl,zodValidator:()=>_o});Ro.exports=Ka(fo);function Xa(...r){return r.reduce((e,t)=>({...e,...t??{}}),{})}function Ya(r){return new ReadableStream({async pull(e){try{let{value:t,done:n}=await r.next();n?e.close():e.enqueue(t);}catch(t){e.error(t);}},cancel(){}})}async function Qa(r){return r==null?Promise.resolve():new Promise(e=>setTimeout(e,r))}function ho(){let r="",e,t=[],n,o;function s(l,u){if(l===""){i(u);return}if(l.startsWith(":"))return;let c=l.indexOf(":");if(c===-1){a(l,"");return}let m=l.slice(0,c),p=c+1,g=p<l.length&&l[p]===" "?l.slice(p+1):l.slice(p);a(m,g);}function i(l){t.length>0&&(l.enqueue({event:e,data:t.join(`
19
+ `),id:n,retry:o}),t=[],e=void 0,o=void 0);}function a(l,u){switch(l){case "event":e=u;break;case "data":t.push(u);break;case "id":n=u;break;case "retry":let c=parseInt(u,10);isNaN(c)||(o=c);break}}return new TransformStream({transform(l,u){let{lines:c,incompleteLine:m}=Za(r,l);r=m;for(let p=0;p<c.length;p++)s(c[p],u);},flush(l){s(r,l),i(l);}})}function Za(r,e){let t=[],n=r;for(let o=0;o<e.length;){let s=e[o++];s===`
20
20
  `?(t.push(n),n=""):s==="\r"?(t.push(n),n="",e[o]===`
21
- `&&o++):n+=s;}return {lines:t,incompleteLine:n}}function fe(r){let e={};return r.headers.forEach((t,n)=>{e[n]=t;}),e}var Va=L(),Ka=to(),co=({prefix:r,size:e=16,alphabet:t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=(0, Ka.customAlphabet)(t,e);if(r==null)return o;if(t.includes(n))throw new Va.InvalidArgumentError({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${t}".`});return s=>`${r}${n}${o(s)}`},Ga=co();function Xa(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var Ve=L();function ir(r){return Object.fromEntries(Object.entries(r).filter(([e,t])=>t!=null))}function Pe(r){return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")}var Ya=()=>globalThis.fetch,Qa=async({url:r,headers:e={},successfulResponseHandler:t,failedResponseHandler:n,abortSignal:o,fetch:s=Ya()})=>{try{let i=await s(r,{method:"GET",headers:ir(e),signal:o}),a=fe(i);if(!i.ok){let l;try{l=await n({response:i,url:r,requestBodyValues:{}});}catch(u){throw Pe(u)||Ve.APICallError.isInstance(u)?u:new Ve.APICallError({message:"Failed to process error response",cause:u,statusCode:i.status,url:r,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await t({response:i,url:r,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Pe(l)||Ve.APICallError.isInstance(l))?l:new Ve.APICallError({message:"Failed to process successful response",cause:l,statusCode:i.status,url:r,responseHeaders:a,requestBodyValues:{}})}}catch(i){if(Pe(i))throw i;if(i instanceof TypeError&&i.message==="fetch failed"){let a=i.cause;if(a!=null)throw new Ve.APICallError({message:`Cannot connect to API: ${a.message}`,cause:a,url:r,isRetryable:true,requestBodyValues:{}})}throw i}},yt=L();function Za({apiKey:r,environmentVariableName:e,apiKeyParameterName:t="apiKey",description:n}){if(typeof r=="string")return r;if(r!=null)throw new yt.LoadAPIKeyError({message:`${n} API key must be a string.`});if(typeof process>"u")throw new yt.LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new yt.LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new yt.LoadAPIKeyError({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return r}function el({settingValue:r,environmentVariableName:e}){if(typeof r=="string")return r;if(!(r!=null||typeof process>"u")&&(r=process.env[e],!(r==null||typeof r!="string")))return r}var vt=L();function tl({settingValue:r,environmentVariableName:e,settingName:t,description:n}){if(typeof r=="string")return r;if(r!=null)throw new vt.LoadSettingError({message:`${n} setting must be a string.`});if(typeof process>"u")throw new vt.LoadSettingError({message:`${n} setting is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new vt.LoadSettingError({message:`${n} setting is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new vt.LoadSettingError({message:`${n} setting must be a string. The value of the ${e} environment variable is not a string.`});return r}var Ge=L(),ar=qa(io()),sr=L(),wt=Symbol.for("vercel.ai.validator");function po(r){return {[wt]:true,validate:r}}function go(r){return typeof r=="object"&&r!==null&&wt in r&&r[wt]===true&&"validate"in r}function mo(r){return go(r)?r:fo(r)}function fo(r){return po(e=>{let t=r.safeParse(e);return t.success?{success:true,value:t.data}:{success:false,error:t.error}})}function ho({value:r,schema:e}){let t=_t({value:r,schema:e});if(!t.success)throw sr.TypeValidationError.wrap({value:r,cause:t.error});return t.value}function _t({value:r,schema:e}){let t=mo(e);try{if(t.validate==null)return {success:!0,value:r};let n=t.validate(r);return n.success?n:{success:!1,error:sr.TypeValidationError.wrap({value:r,cause:n.error})}}catch(n){return {success:false,error:sr.TypeValidationError.wrap({value:r,cause:n})}}}function yo({text:r,schema:e}){try{let t=ar.default.parse(r);return e==null?t:ho({value:t,schema:e})}catch(t){throw Ge.JSONParseError.isInstance(t)||Ge.TypeValidationError.isInstance(t)?t:new Ge.JSONParseError({text:r,cause:t})}}function xt({text:r,schema:e}){try{let t=ar.default.parse(r);if(e==null)return {success:!0,value:t,rawValue:t};let n=_t({value:t,schema:e});return n.success?{...n,rawValue:t}:n}catch(t){return {success:false,error:Ge.JSONParseError.isInstance(t)?t:new Ge.JSONParseError({text:r,cause:t})}}}function rl(r){try{return ar.default.parse(r),!0}catch{return false}}var nl=L();function ol({provider:r,providerOptions:e,schema:t}){if(e?.[r]==null)return;let n=_t({value:e[r],schema:t});if(!n.success)throw new nl.InvalidArgumentError({argument:"providerOptions",message:`invalid ${r} provider options`,cause:n.error});return n.value}var Ke=L(),sl=()=>globalThis.fetch,il=async({url:r,headers:e,body:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>lr({url:r,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(t),values:t},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),al=async({url:r,headers:e,formData:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>lr({url:r,headers:e,body:{content:t,values:Object.fromEntries(t.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),lr=async({url:r,headers:e={},body:t,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=sl()})=>{try{let a=await i(r,{method:"POST",headers:ir(e),body:t.content,signal:s}),l=fe(a);if(!a.ok){let u;try{u=await o({response:a,url:r,requestBodyValues:t.values});}catch(c){throw Pe(c)||Ke.APICallError.isInstance(c)?c:new Ke.APICallError({message:"Failed to process error response",cause:c,statusCode:a.status,url:r,responseHeaders:l,requestBodyValues:t.values})}throw u.value}try{return await n({response:a,url:r,requestBodyValues:t.values})}catch(u){throw u instanceof Error&&(Pe(u)||Ke.APICallError.isInstance(u))?u:new Ke.APICallError({message:"Failed to process successful response",cause:u,statusCode:a.status,url:r,responseHeaders:l,requestBodyValues:t.values})}}catch(a){if(Pe(a))throw a;if(a instanceof TypeError&&a.message==="fetch failed"){let l=a.cause;if(l!=null)throw new Ke.APICallError({message:`Cannot connect to API: ${l.message}`,cause:l,url:r,requestBodyValues:t.values,isRetryable:true})}throw a}};async function ll(r){return typeof r=="function"&&(r=r()),Promise.resolve(r)}var me=L(),ul=({errorSchema:r,errorToMessage:e,isRetryable:t})=>async({response:n,url:o,requestBodyValues:s})=>{let i=await n.text(),a=fe(n);if(i.trim()==="")return {responseHeaders:a,value:new me.APICallError({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:t?.(n)})};try{let l=yo({text:i,schema:r});return {responseHeaders:a,value:new me.APICallError({message:e(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:t?.(n,l)})}}catch{return {responseHeaders:a,value:new me.APICallError({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:t?.(n)})}}},cl=r=>async({response:e})=>{let t=fe(e);if(e.body==null)throw new me.EmptyResponseBodyError({});return {responseHeaders:t,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(uo()).pipeThrough(new TransformStream({transform({data:n},o){n!=="[DONE]"&&o.enqueue(xt({text:n,schema:r}));}}))}},dl=r=>async({response:e})=>{let t=fe(e);if(e.body==null)throw new me.EmptyResponseBodyError({});let n="";return {responseHeaders:t,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(o,s){o.endsWith(`
22
- `)?(s.enqueue(xt({text:n+o,schema:r})),n=""):n+=o;}}))}},pl=r=>async({response:e,url:t,requestBodyValues:n})=>{let o=await e.text(),s=xt({text:o,schema:r}),i=fe(e);if(!s.success)throw new me.APICallError({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:i,responseBody:o,url:t,requestBodyValues:n});return {responseHeaders:i,value:s.value,rawValue:s.rawValue}},gl=()=>async({response:r,url:e,requestBodyValues:t})=>{let n=fe(r);if(!r.body)throw new me.APICallError({message:"Response body is empty",url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:void 0});try{let o=await r.arrayBuffer();return {responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new me.APICallError({message:"Failed to read response as array buffer",url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:void 0,cause:o})}},ml=()=>async({response:r,url:e,requestBodyValues:t})=>{let n=fe(r),o=await r.text();return {responseHeaders:n,value:new me.APICallError({message:r.statusText,url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:o})}},{btoa:fl,atob:hl}=globalThis;function yl(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=hl(e);return Uint8Array.from(t,n=>n.codePointAt(0))}function vl(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCodePoint(r[t]);return fl(e)}function wl(r){return r?.replace(/\/$/,"")}});var hr=_e((Dm,So)=>{y();var mr=Object.defineProperty,bl=Object.getOwnPropertyDescriptor,_l=Object.getOwnPropertyNames,xl=Object.prototype.hasOwnProperty,kl=(r,e)=>{for(var t in e)mr(r,t,{get:e[t],enumerable:true});},Rl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _l(e))!xl.call(r,o)&&o!==t&&mr(r,o,{get:()=>e[o],enumerable:!(n=bl(e,o))||n.enumerable});return r},Cl=r=>Rl(mr({},"__esModule",{value:true}),r),To={};kl(To,{createOpenAI:()=>Ao,openai:()=>Au});So.exports=Cl(To);var wo=V(),Xe=L(),Z=V(),A=U("zod"),ur=L(),Tl=V();function Pl({prompt:r,useLegacyFunctionCalling:e=false,systemMessageMode:t="system"}){let n=[],o=[];for(let{role:s,content:i}of r)switch(s){case "system":{switch(t){case "system":{n.push({role:"system",content:i});break}case "developer":{n.push({role:"developer",content:i});break}case "remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{let a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case "user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,l)=>{var u,c,p,g;switch(a.type){case "text":return {type:"text",text:a.text};case "image":return {type:"image_url",image_url:{url:a.image instanceof URL?a.image.toString():`data:${(u=a.mimeType)!=null?u:"image/jpeg"};base64,${(0, Tl.convertUint8ArrayToBase64)(a.image)}`,detail:(p=(c=a.providerMetadata)==null?void 0:c.openai)==null?void 0:p.imageDetail}};case "file":{if(a.data instanceof URL)throw new ur.UnsupportedFunctionalityError({functionality:"'File content parts with URL data' functionality not supported."});switch(a.mimeType){case "audio/wav":return {type:"input_audio",input_audio:{data:a.data,format:"wav"}};case "audio/mp3":case "audio/mpeg":return {type:"input_audio",input_audio:{data:a.data,format:"mp3"}};case "application/pdf":return {type:"file",file:{filename:(g=a.filename)!=null?g:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${a.data}`}};default:throw new ur.UnsupportedFunctionalityError({functionality:`File content part type ${a.mimeType} in user messages`})}}}})});break}case "assistant":{let a="",l=[];for(let u of i)switch(u.type){case "text":{a+=u.text;break}case "tool-call":{l.push({id:u.toolCallId,type:"function",function:{name:u.toolName,arguments:JSON.stringify(u.args)}});break}}if(e){if(l.length>1)throw new ur.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling with multiple tool calls in one message"});n.push({role:"assistant",content:a,function_call:l.length>0?l[0].function:void 0});}else n.push({role:"assistant",content:a,tool_calls:l.length>0?l:void 0});break}case "tool":{for(let a of i)e?n.push({role:"function",name:a.toolName,content:JSON.stringify(a.result)}):n.push({role:"tool",tool_call_id:a.toolCallId,content:JSON.stringify(a.result)});break}default:{let a=s;throw new Error(`Unsupported role: ${a}`)}}return {messages:n,warnings:o}}function bo(r){var e,t;return (t=(e=r?.content)==null?void 0:e.map(({token:n,logprob:o,top_logprobs:s})=>({token:n,logprob:o,topLogprobs:s?s.map(({token:i,logprob:a})=>({token:i,logprob:a})):[]})))!=null?t:void 0}function Pt(r){switch(r){case "stop":return "stop";case "length":return "length";case "content_filter":return "content-filter";case "function_call":case "tool_calls":return "tool-calls";default:return "unknown"}}var we=U("zod"),El=V(),fr=we.z.object({error:we.z.object({message:we.z.string(),type:we.z.string().nullish(),param:we.z.any().nullish(),code:we.z.union([we.z.string(),we.z.number()]).nullish()})}),ue=(0, El.createJsonErrorResponseHandler)({errorSchema:fr,errorToMessage:r=>r.error.message});function Et({id:r,model:e,created:t}){return {id:r??void 0,modelId:e??void 0,timestamp:t!=null?new Date(t*1e3):void 0}}var _o=L();function Al({mode:r,useLegacyFunctionCalling:e=false,structuredOutputs:t}){var n;let o=(n=r.tools)!=null&&n.length?r.tools:void 0,s=[];if(o==null)return {tools:void 0,tool_choice:void 0,toolWarnings:s};let i=r.toolChoice;if(e){let u=[];for(let p of o)p.type==="provider-defined"?s.push({type:"unsupported-tool",tool:p}):u.push({name:p.name,description:p.description,parameters:p.parameters});if(i==null)return {functions:u,function_call:void 0,toolWarnings:s};switch(i.type){case "auto":case "none":case void 0:return {functions:u,function_call:void 0,toolWarnings:s};case "required":throw new _o.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling and toolChoice: required"});default:return {functions:u,function_call:{name:i.toolName},toolWarnings:s}}}let a=[];for(let u of o)u.type==="provider-defined"?s.push({type:"unsupported-tool",tool:u}):a.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters,strict:t?true:void 0}});if(i==null)return {tools:a,tool_choice:void 0,toolWarnings:s};let l=i.type;switch(l){case "auto":case "none":case "required":return {tools:a,tool_choice:l,toolWarnings:s};case "tool":return {tools:a,tool_choice:{type:"function",function:{name:i.toolName}},toolWarnings:s};default:{let u=l;throw new _o.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${u}`})}}}var Sl=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get supportsStructuredOutputs(){var r;return (r=this.settings.structuredOutputs)!=null?r:gr(this.modelId)}get defaultObjectGenerationMode(){return zl(this.modelId)?"tool":this.supportsStructuredOutputs?"json":"tool"}get provider(){return this.config.provider}get supportsImageUrls(){return !this.settings.downloadImages}getArgs({mode:r,prompt:e,maxTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:c,providerMetadata:p}){var g,m,v,f,d,h,_,C;let w=r.type,x=[];s!=null&&x.push({type:"unsupported-setting",setting:"topK"}),u?.type==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&x.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let S=this.settings.useLegacyFunctionCalling;if(S&&this.settings.parallelToolCalls===true)throw new Xe.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(S&&this.supportsStructuredOutputs)throw new Xe.UnsupportedFunctionalityError({functionality:"structuredOutputs with useLegacyFunctionCalling"});let{messages:z,warnings:T}=Pl({prompt:e,useLegacyFunctionCalling:S,systemMessageMode:Ml(this.modelId)});x.push(...T);let k={model:this.modelId,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===true||typeof this.settings.logprobs=="number"?true:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:t,temperature:n,top_p:o,frequency_penalty:i,presence_penalty:a,response_format:u?.type==="json"?this.supportsStructuredOutputs&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,strict:true,name:(g=u.name)!=null?g:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:c,max_completion_tokens:(m=p?.openai)==null?void 0:m.maxCompletionTokens,store:(v=p?.openai)==null?void 0:v.store,metadata:(f=p?.openai)==null?void 0:f.metadata,prediction:(d=p?.openai)==null?void 0:d.prediction,reasoning_effort:(_=(h=p?.openai)==null?void 0:h.reasoningEffort)!=null?_:this.settings.reasoningEffort,messages:z};switch(gr(this.modelId)?(k.temperature!=null&&(k.temperature=void 0,x.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,x.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,x.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,x.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,x.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,x.push({type:"other",message:"logprobs is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,x.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,x.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w){case "regular":{let{tools:O,tool_choice:I,functions:W,function_call:G,toolWarnings:H}=Al({mode:r,useLegacyFunctionCalling:S,structuredOutputs:this.supportsStructuredOutputs});return {args:{...k,tools:O,tool_choice:I,functions:W,function_call:G},warnings:[...x,...H]}}case "object-json":return {args:{...k,response_format:this.supportsStructuredOutputs&&r.schema!=null?{type:"json_schema",json_schema:{schema:r.schema,strict:true,name:(C=r.name)!=null?C:"response",description:r.description}}:{type:"json_object"}},warnings:x};case "object-tool":return {args:S?{...k,function_call:{name:r.tool.name},functions:[{name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters}]}:{...k,tool_choice:{type:"function",function:{name:r.tool.name}},tools:[{type:"function",function:{name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters,strict:this.supportsStructuredOutputs?true:void 0}}]},warnings:x};default:{let O=w;throw new Error(`Unsupported type: ${O}`)}}}async doGenerate(r){var e,t,n,o,s,i,a,l;let{args:u,warnings:c}=this.getArgs(r),{responseHeaders:p,value:g,rawValue:m}=await(0, Z.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0, Z.combineHeaders)(this.config.headers(),r.headers),body:u,failedResponseHandler:ue,successfulResponseHandler:(0, Z.createJsonResponseHandler)(Il),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:v,...f}=u,d=g.choices[0],h=(e=g.usage)==null?void 0:e.completion_tokens_details,_=(t=g.usage)==null?void 0:t.prompt_tokens_details,C={openai:{}};return h?.reasoning_tokens!=null&&(C.openai.reasoningTokens=h?.reasoning_tokens),h?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=h?.accepted_prediction_tokens),h?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=h?.rejected_prediction_tokens),_?.cached_tokens!=null&&(C.openai.cachedPromptTokens=_?.cached_tokens),{text:(n=d.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&d.message.function_call?[{toolCallType:"function",toolCallId:(0, Z.generateId)(),toolName:d.message.function_call.name,args:d.message.function_call.arguments}]:(o=d.message.tool_calls)==null?void 0:o.map(w=>{var x;return {toolCallType:"function",toolCallId:(x=w.id)!=null?x:(0, Z.generateId)(),toolName:w.function.name,args:w.function.arguments}}),finishReason:Pt(d.finish_reason),usage:{promptTokens:(i=(s=g.usage)==null?void 0:s.prompt_tokens)!=null?i:NaN,completionTokens:(l=(a=g.usage)==null?void 0:a.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:v,rawSettings:f},rawResponse:{headers:p,body:m},request:{body:JSON.stringify(u)},response:Et(g),warnings:c,logprobs:bo(d.logprobs),providerMetadata:C}}async doStream(r){if(this.settings.simulateStreaming){let f=await this.doGenerate(r);return {stream:new ReadableStream({start(h){if(h.enqueue({type:"response-metadata",...f.response}),f.text&&h.enqueue({type:"text-delta",textDelta:f.text}),f.toolCalls)for(let _ of f.toolCalls)h.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:_.toolCallId,toolName:_.toolName,argsTextDelta:_.args}),h.enqueue({type:"tool-call",..._});h.enqueue({type:"finish",finishReason:f.finishReason,usage:f.usage,logprobs:f.logprobs,providerMetadata:f.providerMetadata}),h.close();}}),rawCall:f.rawCall,rawResponse:f.rawResponse,warnings:f.warnings}}let{args:e,warnings:t}=this.getArgs(r),n={...e,stream:true,stream_options:this.config.compatibility==="strict"?{include_usage:true}:void 0},{responseHeaders:o,value:s}=await(0, Z.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0, Z.combineHeaders)(this.config.headers(),r.headers),body:n,failedResponseHandler:ue,successfulResponseHandler:(0, Z.createEventSourceResponseHandler)(Ol),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:i,...a}=e,l=[],u="unknown",c={promptTokens:void 0,completionTokens:void 0},p,g=true,{useLegacyFunctionCalling:m}=this.settings,v={openai:{}};return {stream:s.pipeThrough(new TransformStream({transform(f,d){var h,_,C,w,x,S,z,T,k,O,I,W;if(!f.success){u="error",d.enqueue({type:"error",error:f.error});return}let G=f.value;if("error"in G){u="error",d.enqueue({type:"error",error:G.error});return}if(g&&(g=false,d.enqueue({type:"response-metadata",...Et(G)})),G.usage!=null){let{prompt_tokens:q,completion_tokens:Y,prompt_tokens_details:J,completion_tokens_details:F}=G.usage;c={promptTokens:q??void 0,completionTokens:Y??void 0},F?.reasoning_tokens!=null&&(v.openai.reasoningTokens=F?.reasoning_tokens),F?.accepted_prediction_tokens!=null&&(v.openai.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(v.openai.rejectedPredictionTokens=F?.rejected_prediction_tokens),J?.cached_tokens!=null&&(v.openai.cachedPromptTokens=J?.cached_tokens);}let H=G.choices[0];if(H?.finish_reason!=null&&(u=Pt(H.finish_reason)),H?.delta==null)return;let be=H.delta;be.content!=null&&d.enqueue({type:"text-delta",textDelta:be.content});let te=bo(H?.logprobs);te?.length&&(p===void 0&&(p=[]),p.push(...te));let ne=m&&be.function_call!=null?[{type:"function",id:(0, Z.generateId)(),function:be.function_call,index:0}]:be.tool_calls;if(ne!=null)for(let q of ne){let Y=q.index;if(l[Y]==null){if(q.type!=="function")throw new Xe.InvalidResponseDataError({data:q,message:"Expected 'function' type."});if(q.id==null)throw new Xe.InvalidResponseDataError({data:q,message:"Expected 'id' to be a string."});if(((h=q.function)==null?void 0:h.name)==null)throw new Xe.InvalidResponseDataError({data:q,message:"Expected 'function.name' to be a string."});l[Y]={id:q.id,type:"function",function:{name:q.function.name,arguments:(_=q.function.arguments)!=null?_:""},hasFinished:false};let F=l[Y];((C=F.function)==null?void 0:C.name)!=null&&((w=F.function)==null?void 0:w.arguments)!=null&&(F.function.arguments.length>0&&d.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:F.id,toolName:F.function.name,argsTextDelta:F.function.arguments}),(0, Z.isParsableJson)(F.function.arguments)&&(d.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(x=F.id)!=null?x:(0, Z.generateId)(),toolName:F.function.name,args:F.function.arguments}),F.hasFinished=true));continue}let J=l[Y];J.hasFinished||(((S=q.function)==null?void 0:S.arguments)!=null&&(J.function.arguments+=(T=(z=q.function)==null?void 0:z.arguments)!=null?T:""),d.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:J.id,toolName:J.function.name,argsTextDelta:(k=q.function.arguments)!=null?k:""}),((O=J.function)==null?void 0:O.name)!=null&&((I=J.function)==null?void 0:I.arguments)!=null&&(0, Z.isParsableJson)(J.function.arguments)&&(d.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(W=J.id)!=null?W:(0, Z.generateId)(),toolName:J.function.name,args:J.function.arguments}),J.hasFinished=true));}},flush(f){var d,h;f.enqueue({type:"finish",finishReason:u,logprobs:p,usage:{promptTokens:(d=c.promptTokens)!=null?d:NaN,completionTokens:(h=c.completionTokens)!=null?h:NaN},...v!=null?{providerMetadata:v}:{}});}})),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:o},request:{body:JSON.stringify(n)},warnings:t}}},Po=A.z.object({prompt_tokens:A.z.number().nullish(),completion_tokens:A.z.number().nullish(),prompt_tokens_details:A.z.object({cached_tokens:A.z.number().nullish()}).nullish(),completion_tokens_details:A.z.object({reasoning_tokens:A.z.number().nullish(),accepted_prediction_tokens:A.z.number().nullish(),rejected_prediction_tokens:A.z.number().nullish()}).nullish()}).nullish(),Il=A.z.object({id:A.z.string().nullish(),created:A.z.number().nullish(),model:A.z.string().nullish(),choices:A.z.array(A.z.object({message:A.z.object({role:A.z.literal("assistant").nullish(),content:A.z.string().nullish(),function_call:A.z.object({arguments:A.z.string(),name:A.z.string()}).nullish(),tool_calls:A.z.array(A.z.object({id:A.z.string().nullish(),type:A.z.literal("function"),function:A.z.object({name:A.z.string(),arguments:A.z.string()})})).nullish()}),index:A.z.number(),logprobs:A.z.object({content:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number(),top_logprobs:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number()}))})).nullable()}).nullish(),finish_reason:A.z.string().nullish()})),usage:Po}),Ol=A.z.union([A.z.object({id:A.z.string().nullish(),created:A.z.number().nullish(),model:A.z.string().nullish(),choices:A.z.array(A.z.object({delta:A.z.object({role:A.z.enum(["assistant"]).nullish(),content:A.z.string().nullish(),function_call:A.z.object({name:A.z.string().optional(),arguments:A.z.string().optional()}).nullish(),tool_calls:A.z.array(A.z.object({index:A.z.number(),id:A.z.string().nullish(),type:A.z.literal("function").nullish(),function:A.z.object({name:A.z.string().nullish(),arguments:A.z.string().nullish()})})).nullish()}).nullish(),logprobs:A.z.object({content:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number(),top_logprobs:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number()}))})).nullable()}).nullish(),finish_reason:A.z.string().nullish(),index:A.z.number()})),usage:Po}),fr]);function gr(r){return r.startsWith("o")||r.startsWith("gpt-5")}function zl(r){return r.startsWith("gpt-4o-audio-preview")}function Ml(r){var e,t;return gr(r)?(t=(e=jl[r])==null?void 0:e.systemMessageMode)!=null?t:"developer":"system"}var jl={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}},kt=L(),ze=V(),j=U("zod"),Rt=L();function Nl({prompt:r,inputFormat:e,user:t="user",assistant:n="assistant"}){if(e==="prompt"&&r.length===1&&r[0].role==="user"&&r[0].content.length===1&&r[0].content[0].type==="text")return {prompt:r[0].content[0].text};let o="";r[0].role==="system"&&(o+=`${r[0].content}
21
+ `&&o++):n+=s;}return {lines:t,incompleteLine:n}}function fe(r){let e={};return r.headers.forEach((t,n)=>{e[n]=t;}),e}var el=q(),tl=ao(),yo=({prefix:r,size:e=16,alphabet:t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=(0, tl.customAlphabet)(t,e);if(r==null)return o;if(t.includes(n))throw new el.InvalidArgumentError({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${t}".`});return s=>`${r}${n}${o(s)}`},rl=yo();function nl(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var Ve=q();function cr(r){return Object.fromEntries(Object.entries(r).filter(([e,t])=>t!=null))}function Pe(r){return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")}var ol=()=>globalThis.fetch,sl=async({url:r,headers:e={},successfulResponseHandler:t,failedResponseHandler:n,abortSignal:o,fetch:s=ol()})=>{try{let i=await s(r,{method:"GET",headers:cr(e),signal:o}),a=fe(i);if(!i.ok){let l;try{l=await n({response:i,url:r,requestBodyValues:{}});}catch(u){throw Pe(u)||Ve.APICallError.isInstance(u)?u:new Ve.APICallError({message:"Failed to process error response",cause:u,statusCode:i.status,url:r,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await t({response:i,url:r,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Pe(l)||Ve.APICallError.isInstance(l))?l:new Ve.APICallError({message:"Failed to process successful response",cause:l,statusCode:i.status,url:r,responseHeaders:a,requestBodyValues:{}})}}catch(i){if(Pe(i))throw i;if(i instanceof TypeError&&i.message==="fetch failed"){let a=i.cause;if(a!=null)throw new Ve.APICallError({message:`Cannot connect to API: ${a.message}`,cause:a,url:r,isRetryable:true,requestBodyValues:{}})}throw i}},yt=q();function il({apiKey:r,environmentVariableName:e,apiKeyParameterName:t="apiKey",description:n}){if(typeof r=="string")return r;if(r!=null)throw new yt.LoadAPIKeyError({message:`${n} API key must be a string.`});if(typeof process>"u")throw new yt.LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new yt.LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new yt.LoadAPIKeyError({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return r}function al({settingValue:r,environmentVariableName:e}){if(typeof r=="string")return r;if(!(r!=null||typeof process>"u")&&(r=process.env[e],!(r==null||typeof r!="string")))return r}var vt=q();function ll({settingValue:r,environmentVariableName:e,settingName:t,description:n}){if(typeof r=="string")return r;if(r!=null)throw new vt.LoadSettingError({message:`${n} setting must be a string.`});if(typeof process>"u")throw new vt.LoadSettingError({message:`${n} setting is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new vt.LoadSettingError({message:`${n} setting is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new vt.LoadSettingError({message:`${n} setting must be a string. The value of the ${e} environment variable is not a string.`});return r}var Ke=q(),dr=Ga(go()),ur=q(),wt=Symbol.for("vercel.ai.validator");function vo(r){return {[wt]:true,validate:r}}function wo(r){return typeof r=="object"&&r!==null&&wt in r&&r[wt]===true&&"validate"in r}function bo(r){return wo(r)?r:_o(r)}function _o(r){return vo(e=>{let t=r.safeParse(e);return t.success?{success:true,value:t.data}:{success:false,error:t.error}})}function xo({value:r,schema:e}){let t=_t({value:r,schema:e});if(!t.success)throw ur.TypeValidationError.wrap({value:r,cause:t.error});return t.value}function _t({value:r,schema:e}){let t=bo(e);try{if(t.validate==null)return {success:!0,value:r};let n=t.validate(r);return n.success?n:{success:!1,error:ur.TypeValidationError.wrap({value:r,cause:n.error})}}catch(n){return {success:false,error:ur.TypeValidationError.wrap({value:r,cause:n})}}}function ko({text:r,schema:e}){try{let t=dr.default.parse(r);return e==null?t:xo({value:t,schema:e})}catch(t){throw Ke.JSONParseError.isInstance(t)||Ke.TypeValidationError.isInstance(t)?t:new Ke.JSONParseError({text:r,cause:t})}}function xt({text:r,schema:e}){try{let t=dr.default.parse(r);if(e==null)return {success:!0,value:t,rawValue:t};let n=_t({value:t,schema:e});return n.success?{...n,rawValue:t}:n}catch(t){return {success:false,error:Ke.JSONParseError.isInstance(t)?t:new Ke.JSONParseError({text:r,cause:t})}}}function ul(r){try{return dr.default.parse(r),!0}catch{return false}}var cl=q();function dl({provider:r,providerOptions:e,schema:t}){if(e?.[r]==null)return;let n=_t({value:e[r],schema:t});if(!n.success)throw new cl.InvalidArgumentError({argument:"providerOptions",message:`invalid ${r} provider options`,cause:n.error});return n.value}var Ge=q(),pl=()=>globalThis.fetch,gl=async({url:r,headers:e,body:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>pr({url:r,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(t),values:t},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),ml=async({url:r,headers:e,formData:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>pr({url:r,headers:e,body:{content:t,values:Object.fromEntries(t.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),pr=async({url:r,headers:e={},body:t,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=pl()})=>{try{let a=await i(r,{method:"POST",headers:cr(e),body:t.content,signal:s}),l=fe(a);if(!a.ok){let u;try{u=await o({response:a,url:r,requestBodyValues:t.values});}catch(c){throw Pe(c)||Ge.APICallError.isInstance(c)?c:new Ge.APICallError({message:"Failed to process error response",cause:c,statusCode:a.status,url:r,responseHeaders:l,requestBodyValues:t.values})}throw u.value}try{return await n({response:a,url:r,requestBodyValues:t.values})}catch(u){throw u instanceof Error&&(Pe(u)||Ge.APICallError.isInstance(u))?u:new Ge.APICallError({message:"Failed to process successful response",cause:u,statusCode:a.status,url:r,responseHeaders:l,requestBodyValues:t.values})}}catch(a){if(Pe(a))throw a;if(a instanceof TypeError&&a.message==="fetch failed"){let l=a.cause;if(l!=null)throw new Ge.APICallError({message:`Cannot connect to API: ${l.message}`,cause:l,url:r,requestBodyValues:t.values,isRetryable:true})}throw a}};async function fl(r){return typeof r=="function"&&(r=r()),Promise.resolve(r)}var me=q(),hl=({errorSchema:r,errorToMessage:e,isRetryable:t})=>async({response:n,url:o,requestBodyValues:s})=>{let i=await n.text(),a=fe(n);if(i.trim()==="")return {responseHeaders:a,value:new me.APICallError({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:t?.(n)})};try{let l=ko({text:i,schema:r});return {responseHeaders:a,value:new me.APICallError({message:e(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:t?.(n,l)})}}catch{return {responseHeaders:a,value:new me.APICallError({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:t?.(n)})}}},yl=r=>async({response:e})=>{let t=fe(e);if(e.body==null)throw new me.EmptyResponseBodyError({});return {responseHeaders:t,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(ho()).pipeThrough(new TransformStream({transform({data:n},o){n!=="[DONE]"&&o.enqueue(xt({text:n,schema:r}));}}))}},vl=r=>async({response:e})=>{let t=fe(e);if(e.body==null)throw new me.EmptyResponseBodyError({});let n="";return {responseHeaders:t,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(o,s){o.endsWith(`
22
+ `)?(s.enqueue(xt({text:n+o,schema:r})),n=""):n+=o;}}))}},wl=r=>async({response:e,url:t,requestBodyValues:n})=>{let o=await e.text(),s=xt({text:o,schema:r}),i=fe(e);if(!s.success)throw new me.APICallError({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:i,responseBody:o,url:t,requestBodyValues:n});return {responseHeaders:i,value:s.value,rawValue:s.rawValue}},bl=()=>async({response:r,url:e,requestBodyValues:t})=>{let n=fe(r);if(!r.body)throw new me.APICallError({message:"Response body is empty",url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:void 0});try{let o=await r.arrayBuffer();return {responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new me.APICallError({message:"Failed to read response as array buffer",url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:void 0,cause:o})}},_l=()=>async({response:r,url:e,requestBodyValues:t})=>{let n=fe(r),o=await r.text();return {responseHeaders:n,value:new me.APICallError({message:r.statusText,url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:o})}},{btoa:xl,atob:kl}=globalThis;function Rl(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=kl(e);return Uint8Array.from(t,n=>n.codePointAt(0))}function Cl(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCodePoint(r[t]);return xl(e)}function Tl(r){return r?.replace(/\/$/,"")}});var br=_e((Gm,No)=>{h();var vr=Object.defineProperty,Pl=Object.getOwnPropertyDescriptor,El=Object.getOwnPropertyNames,Al=Object.prototype.hasOwnProperty,Sl=(r,e)=>{for(var t in e)vr(r,t,{get:e[t],enumerable:true});},Il=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of El(e))!Al.call(r,o)&&o!==t&&vr(r,o,{get:()=>e[o],enumerable:!(n=Pl(e,o))||n.enumerable});return r},Ol=r=>Il(vr({},"__esModule",{value:true}),r),Oo={};Sl(Oo,{createOpenAI:()=>jo,openai:()=>Nu});No.exports=Ol(Oo);var Co=G(),Xe=q(),Z=G(),A=J("zod"),gr=q(),zl=G();function Ml({prompt:r,useLegacyFunctionCalling:e=false,systemMessageMode:t="system"}){let n=[],o=[];for(let{role:s,content:i}of r)switch(s){case "system":{switch(t){case "system":{n.push({role:"system",content:i});break}case "developer":{n.push({role:"developer",content:i});break}case "remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{let a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case "user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,l)=>{var u,c,m,p;switch(a.type){case "text":return {type:"text",text:a.text};case "image":return {type:"image_url",image_url:{url:a.image instanceof URL?a.image.toString():`data:${(u=a.mimeType)!=null?u:"image/jpeg"};base64,${(0, zl.convertUint8ArrayToBase64)(a.image)}`,detail:(m=(c=a.providerMetadata)==null?void 0:c.openai)==null?void 0:m.imageDetail}};case "file":{if(a.data instanceof URL)throw new gr.UnsupportedFunctionalityError({functionality:"'File content parts with URL data' functionality not supported."});switch(a.mimeType){case "audio/wav":return {type:"input_audio",input_audio:{data:a.data,format:"wav"}};case "audio/mp3":case "audio/mpeg":return {type:"input_audio",input_audio:{data:a.data,format:"mp3"}};case "application/pdf":return {type:"file",file:{filename:(p=a.filename)!=null?p:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${a.data}`}};default:throw new gr.UnsupportedFunctionalityError({functionality:`File content part type ${a.mimeType} in user messages`})}}}})});break}case "assistant":{let a="",l=[];for(let u of i)switch(u.type){case "text":{a+=u.text;break}case "tool-call":{l.push({id:u.toolCallId,type:"function",function:{name:u.toolName,arguments:JSON.stringify(u.args)}});break}}if(e){if(l.length>1)throw new gr.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling with multiple tool calls in one message"});n.push({role:"assistant",content:a,function_call:l.length>0?l[0].function:void 0});}else n.push({role:"assistant",content:a,tool_calls:l.length>0?l:void 0});break}case "tool":{for(let a of i)e?n.push({role:"function",name:a.toolName,content:JSON.stringify(a.result)}):n.push({role:"tool",tool_call_id:a.toolCallId,content:JSON.stringify(a.result)});break}default:{let a=s;throw new Error(`Unsupported role: ${a}`)}}return {messages:n,warnings:o}}function To(r){var e,t;return (t=(e=r?.content)==null?void 0:e.map(({token:n,logprob:o,top_logprobs:s})=>({token:n,logprob:o,topLogprobs:s?s.map(({token:i,logprob:a})=>({token:i,logprob:a})):[]})))!=null?t:void 0}function Pt(r){switch(r){case "stop":return "stop";case "length":return "length";case "content_filter":return "content-filter";case "function_call":case "tool_calls":return "tool-calls";default:return "unknown"}}var we=J("zod"),jl=G(),wr=we.z.object({error:we.z.object({message:we.z.string(),type:we.z.string().nullish(),param:we.z.any().nullish(),code:we.z.union([we.z.string(),we.z.number()]).nullish()})}),ue=(0, jl.createJsonErrorResponseHandler)({errorSchema:wr,errorToMessage:r=>r.error.message});function Et({id:r,model:e,created:t}){return {id:r??void 0,modelId:e??void 0,timestamp:t!=null?new Date(t*1e3):void 0}}var Po=q();function Nl({mode:r,useLegacyFunctionCalling:e=false,structuredOutputs:t}){var n;let o=(n=r.tools)!=null&&n.length?r.tools:void 0,s=[];if(o==null)return {tools:void 0,tool_choice:void 0,toolWarnings:s};let i=r.toolChoice;if(e){let u=[];for(let m of o)m.type==="provider-defined"?s.push({type:"unsupported-tool",tool:m}):u.push({name:m.name,description:m.description,parameters:m.parameters});if(i==null)return {functions:u,function_call:void 0,toolWarnings:s};switch(i.type){case "auto":case "none":case void 0:return {functions:u,function_call:void 0,toolWarnings:s};case "required":throw new Po.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling and toolChoice: required"});default:return {functions:u,function_call:{name:i.toolName},toolWarnings:s}}}let a=[];for(let u of o)u.type==="provider-defined"?s.push({type:"unsupported-tool",tool:u}):a.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters,strict:t?true:void 0}});if(i==null)return {tools:a,tool_choice:void 0,toolWarnings:s};let l=i.type;switch(l){case "auto":case "none":case "required":return {tools:a,tool_choice:l,toolWarnings:s};case "tool":return {tools:a,tool_choice:{type:"function",function:{name:i.toolName}},toolWarnings:s};default:{let u=l;throw new Po.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${u}`})}}}var Dl=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get supportsStructuredOutputs(){var r;return (r=this.settings.structuredOutputs)!=null?r:yr(this.modelId)}get defaultObjectGenerationMode(){return Ll(this.modelId)?"tool":this.supportsStructuredOutputs?"json":"tool"}get provider(){return this.config.provider}get supportsImageUrls(){return !this.settings.downloadImages}getArgs({mode:r,prompt:e,maxTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:c,providerMetadata:m}){var p,g,v,f,d,y,b,k;let w=r.type,x=[];s!=null&&x.push({type:"unsupported-setting",setting:"topK"}),u?.type==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&x.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let S=this.settings.useLegacyFunctionCalling;if(S&&this.settings.parallelToolCalls===true)throw new Xe.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(S&&this.supportsStructuredOutputs)throw new Xe.UnsupportedFunctionalityError({functionality:"structuredOutputs with useLegacyFunctionCalling"});let{messages:z,warnings:R}=Ml({prompt:e,useLegacyFunctionCalling:S,systemMessageMode:ql(this.modelId)});x.push(...R);let T={model:this.modelId,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===true||typeof this.settings.logprobs=="number"?true:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:t,temperature:n,top_p:o,frequency_penalty:i,presence_penalty:a,response_format:u?.type==="json"?this.supportsStructuredOutputs&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,strict:true,name:(p=u.name)!=null?p:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:c,max_completion_tokens:(g=m?.openai)==null?void 0:g.maxCompletionTokens,store:(v=m?.openai)==null?void 0:v.store,metadata:(f=m?.openai)==null?void 0:f.metadata,prediction:(d=m?.openai)==null?void 0:d.prediction,reasoning_effort:(b=(y=m?.openai)==null?void 0:y.reasoningEffort)!=null?b:this.settings.reasoningEffort,messages:z};switch(yr(this.modelId)?(T.temperature!=null&&(T.temperature=void 0,x.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,x.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),T.frequency_penalty!=null&&(T.frequency_penalty=void 0,x.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),T.presence_penalty!=null&&(T.presence_penalty=void 0,x.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),T.logit_bias!=null&&(T.logit_bias=void 0,x.push({type:"other",message:"logitBias is not supported for reasoning models"})),T.logprobs!=null&&(T.logprobs=void 0,x.push({type:"other",message:"logprobs is not supported for reasoning models"})),T.top_logprobs!=null&&(T.top_logprobs=void 0,x.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),T.max_tokens!=null&&(T.max_completion_tokens==null&&(T.max_completion_tokens=T.max_tokens),T.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&T.temperature!=null&&(T.temperature=void 0,x.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w){case "regular":{let{tools:O,tool_choice:j,functions:I,function_call:F,toolWarnings:L}=Nl({mode:r,useLegacyFunctionCalling:S,structuredOutputs:this.supportsStructuredOutputs});return {args:{...T,tools:O,tool_choice:j,functions:I,function_call:F},warnings:[...x,...L]}}case "object-json":return {args:{...T,response_format:this.supportsStructuredOutputs&&r.schema!=null?{type:"json_schema",json_schema:{schema:r.schema,strict:true,name:(k=r.name)!=null?k:"response",description:r.description}}:{type:"json_object"}},warnings:x};case "object-tool":return {args:S?{...T,function_call:{name:r.tool.name},functions:[{name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters}]}:{...T,tool_choice:{type:"function",function:{name:r.tool.name}},tools:[{type:"function",function:{name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters,strict:this.supportsStructuredOutputs?true:void 0}}]},warnings:x};default:{let O=w;throw new Error(`Unsupported type: ${O}`)}}}async doGenerate(r){var e,t,n,o,s,i,a,l;let{args:u,warnings:c}=this.getArgs(r),{responseHeaders:m,value:p,rawValue:g}=await(0, Z.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0, Z.combineHeaders)(this.config.headers(),r.headers),body:u,failedResponseHandler:ue,successfulResponseHandler:(0, Z.createJsonResponseHandler)($l),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:v,...f}=u,d=p.choices[0],y=(e=p.usage)==null?void 0:e.completion_tokens_details,b=(t=p.usage)==null?void 0:t.prompt_tokens_details,k={openai:{}};return y?.reasoning_tokens!=null&&(k.openai.reasoningTokens=y?.reasoning_tokens),y?.accepted_prediction_tokens!=null&&(k.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(k.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),b?.cached_tokens!=null&&(k.openai.cachedPromptTokens=b?.cached_tokens),{text:(n=d.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&d.message.function_call?[{toolCallType:"function",toolCallId:(0, Z.generateId)(),toolName:d.message.function_call.name,args:d.message.function_call.arguments}]:(o=d.message.tool_calls)==null?void 0:o.map(w=>{var x;return {toolCallType:"function",toolCallId:(x=w.id)!=null?x:(0, Z.generateId)(),toolName:w.function.name,args:w.function.arguments}}),finishReason:Pt(d.finish_reason),usage:{promptTokens:(i=(s=p.usage)==null?void 0:s.prompt_tokens)!=null?i:NaN,completionTokens:(l=(a=p.usage)==null?void 0:a.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:v,rawSettings:f},rawResponse:{headers:m,body:g},request:{body:JSON.stringify(u)},response:Et(p),warnings:c,logprobs:To(d.logprobs),providerMetadata:k}}async doStream(r){if(this.settings.simulateStreaming){let f=await this.doGenerate(r);return {stream:new ReadableStream({start(y){if(y.enqueue({type:"response-metadata",...f.response}),f.text&&y.enqueue({type:"text-delta",textDelta:f.text}),f.toolCalls)for(let b of f.toolCalls)y.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:b.toolCallId,toolName:b.toolName,argsTextDelta:b.args}),y.enqueue({type:"tool-call",...b});y.enqueue({type:"finish",finishReason:f.finishReason,usage:f.usage,logprobs:f.logprobs,providerMetadata:f.providerMetadata}),y.close();}}),rawCall:f.rawCall,rawResponse:f.rawResponse,warnings:f.warnings}}let{args:e,warnings:t}=this.getArgs(r),n={...e,stream:true,stream_options:this.config.compatibility==="strict"?{include_usage:true}:void 0},{responseHeaders:o,value:s}=await(0, Z.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0, Z.combineHeaders)(this.config.headers(),r.headers),body:n,failedResponseHandler:ue,successfulResponseHandler:(0, Z.createEventSourceResponseHandler)(Hl),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:i,...a}=e,l=[],u="unknown",c={promptTokens:void 0,completionTokens:void 0},m,p=true,{useLegacyFunctionCalling:g}=this.settings,v={openai:{}};return {stream:s.pipeThrough(new TransformStream({transform(f,d){var y,b,k,w,x,S,z,R,T,O,j,I;if(!f.success){u="error",d.enqueue({type:"error",error:f.error});return}let F=f.value;if("error"in F){u="error",d.enqueue({type:"error",error:F.error});return}if(p&&(p=false,d.enqueue({type:"response-metadata",...Et(F)})),F.usage!=null){let{prompt_tokens:U,completion_tokens:Y,prompt_tokens_details:V,completion_tokens_details:B}=F.usage;c={promptTokens:U??void 0,completionTokens:Y??void 0},B?.reasoning_tokens!=null&&(v.openai.reasoningTokens=B?.reasoning_tokens),B?.accepted_prediction_tokens!=null&&(v.openai.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(v.openai.rejectedPredictionTokens=B?.rejected_prediction_tokens),V?.cached_tokens!=null&&(v.openai.cachedPromptTokens=V?.cached_tokens);}let L=F.choices[0];if(L?.finish_reason!=null&&(u=Pt(L.finish_reason)),L?.delta==null)return;let be=L.delta;be.content!=null&&d.enqueue({type:"text-delta",textDelta:be.content});let te=To(L?.logprobs);te?.length&&(m===void 0&&(m=[]),m.push(...te));let ne=g&&be.function_call!=null?[{type:"function",id:(0, Z.generateId)(),function:be.function_call,index:0}]:be.tool_calls;if(ne!=null)for(let U of ne){let Y=U.index;if(l[Y]==null){if(U.type!=="function")throw new Xe.InvalidResponseDataError({data:U,message:"Expected 'function' type."});if(U.id==null)throw new Xe.InvalidResponseDataError({data:U,message:"Expected 'id' to be a string."});if(((y=U.function)==null?void 0:y.name)==null)throw new Xe.InvalidResponseDataError({data:U,message:"Expected 'function.name' to be a string."});l[Y]={id:U.id,type:"function",function:{name:U.function.name,arguments:(b=U.function.arguments)!=null?b:""},hasFinished:false};let B=l[Y];((k=B.function)==null?void 0:k.name)!=null&&((w=B.function)==null?void 0:w.arguments)!=null&&(B.function.arguments.length>0&&d.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:B.id,toolName:B.function.name,argsTextDelta:B.function.arguments}),(0, Z.isParsableJson)(B.function.arguments)&&(d.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(x=B.id)!=null?x:(0, Z.generateId)(),toolName:B.function.name,args:B.function.arguments}),B.hasFinished=true));continue}let V=l[Y];V.hasFinished||(((S=U.function)==null?void 0:S.arguments)!=null&&(V.function.arguments+=(R=(z=U.function)==null?void 0:z.arguments)!=null?R:""),d.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:V.id,toolName:V.function.name,argsTextDelta:(T=U.function.arguments)!=null?T:""}),((O=V.function)==null?void 0:O.name)!=null&&((j=V.function)==null?void 0:j.arguments)!=null&&(0, Z.isParsableJson)(V.function.arguments)&&(d.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(I=V.id)!=null?I:(0, Z.generateId)(),toolName:V.function.name,args:V.function.arguments}),V.hasFinished=true));}},flush(f){var d,y;f.enqueue({type:"finish",finishReason:u,logprobs:m,usage:{promptTokens:(d=c.promptTokens)!=null?d:NaN,completionTokens:(y=c.completionTokens)!=null?y:NaN},...v!=null?{providerMetadata:v}:{}});}})),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:o},request:{body:JSON.stringify(n)},warnings:t}}},zo=A.z.object({prompt_tokens:A.z.number().nullish(),completion_tokens:A.z.number().nullish(),prompt_tokens_details:A.z.object({cached_tokens:A.z.number().nullish()}).nullish(),completion_tokens_details:A.z.object({reasoning_tokens:A.z.number().nullish(),accepted_prediction_tokens:A.z.number().nullish(),rejected_prediction_tokens:A.z.number().nullish()}).nullish()}).nullish(),$l=A.z.object({id:A.z.string().nullish(),created:A.z.number().nullish(),model:A.z.string().nullish(),choices:A.z.array(A.z.object({message:A.z.object({role:A.z.literal("assistant").nullish(),content:A.z.string().nullish(),function_call:A.z.object({arguments:A.z.string(),name:A.z.string()}).nullish(),tool_calls:A.z.array(A.z.object({id:A.z.string().nullish(),type:A.z.literal("function"),function:A.z.object({name:A.z.string(),arguments:A.z.string()})})).nullish()}),index:A.z.number(),logprobs:A.z.object({content:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number(),top_logprobs:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number()}))})).nullable()}).nullish(),finish_reason:A.z.string().nullish()})),usage:zo}),Hl=A.z.union([A.z.object({id:A.z.string().nullish(),created:A.z.number().nullish(),model:A.z.string().nullish(),choices:A.z.array(A.z.object({delta:A.z.object({role:A.z.enum(["assistant"]).nullish(),content:A.z.string().nullish(),function_call:A.z.object({name:A.z.string().optional(),arguments:A.z.string().optional()}).nullish(),tool_calls:A.z.array(A.z.object({index:A.z.number(),id:A.z.string().nullish(),type:A.z.literal("function").nullish(),function:A.z.object({name:A.z.string().nullish(),arguments:A.z.string().nullish()})})).nullish()}).nullish(),logprobs:A.z.object({content:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number(),top_logprobs:A.z.array(A.z.object({token:A.z.string(),logprob:A.z.number()}))})).nullable()}).nullish(),finish_reason:A.z.string().nullish(),index:A.z.number()})),usage:zo}),wr]);function yr(r){return r.startsWith("o")||r.startsWith("gpt-5")}function Ll(r){return r.startsWith("gpt-4o-audio-preview")}function ql(r){var e,t;return yr(r)?(t=(e=Fl[r])==null?void 0:e.systemMessageMode)!=null?t:"developer":"system"}var Fl={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}},kt=q(),ze=G(),N=J("zod"),Rt=q();function Ul({prompt:r,inputFormat:e,user:t="user",assistant:n="assistant"}){if(e==="prompt"&&r.length===1&&r[0].role==="user"&&r[0].content.length===1&&r[0].content[0].type==="text")return {prompt:r[0].content[0].text};let o="";r[0].role==="system"&&(o+=`${r[0].content}
23
23
 
24
24
  `,r=r.slice(1));for(let{role:s,content:i}of r)switch(s){case "system":throw new Rt.InvalidPromptError({message:"Unexpected system message in prompt: ${content}",prompt:r});case "user":{let a=i.map(l=>{switch(l.type){case "text":return l.text;case "image":throw new Rt.UnsupportedFunctionalityError({functionality:"images"})}}).join("");o+=`${t}:
25
25
  ${a}
@@ -29,24 +29,24 @@ ${a}
29
29
 
30
30
  `;break}case "tool":throw new Rt.UnsupportedFunctionalityError({functionality:"tool messages"});default:{let a=s;throw new Error(`Unsupported role: ${a}`)}}return o+=`${n}:
31
31
  `,{prompt:o,stopSequences:[`
32
- ${t}:`]}}function xo(r){return r?.tokens.map((e,t)=>({token:e,logprob:r.token_logprobs[t],topLogprobs:r.top_logprobs?Object.entries(r.top_logprobs[t]).map(([n,o])=>({token:n,logprob:o})):[]}))}var $l=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode=void 0,this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}getArgs({mode:r,inputFormat:e,prompt:t,maxTokens:n,temperature:o,topP:s,topK:i,frequencyPenalty:a,presencePenalty:l,stopSequences:u,responseFormat:c,seed:p}){var g;let m=r.type,v=[];i!=null&&v.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:f,stopSequences:d}=Nl({prompt:t,inputFormat:e}),h=[...d??[],...u??[]],_={model:this.modelId,echo:this.settings.echo,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:n,temperature:o,top_p:s,frequency_penalty:a,presence_penalty:l,seed:p,prompt:f,stop:h.length>0?h:void 0};switch(m){case "regular":{if((g=r.tools)!=null&&g.length)throw new kt.UnsupportedFunctionalityError({functionality:"tools"});if(r.toolChoice)throw new kt.UnsupportedFunctionalityError({functionality:"toolChoice"});return {args:_,warnings:v}}case "object-json":throw new kt.UnsupportedFunctionalityError({functionality:"object-json mode"});case "object-tool":throw new kt.UnsupportedFunctionalityError({functionality:"object-tool mode"});default:{let C=m;throw new Error(`Unsupported type: ${C}`)}}}async doGenerate(r){let{args:e,warnings:t}=this.getArgs(r),{responseHeaders:n,value:o,rawValue:s}=await(0, ze.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0, ze.combineHeaders)(this.config.headers(),r.headers),body:e,failedResponseHandler:ue,successfulResponseHandler:(0, ze.createJsonResponseHandler)(Dl),abortSignal:r.abortSignal,fetch:this.config.fetch}),{prompt:i,...a}=e,l=o.choices[0];return {text:l.text,usage:{promptTokens:o.usage.prompt_tokens,completionTokens:o.usage.completion_tokens},finishReason:Pt(l.finish_reason),logprobs:xo(l.logprobs),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:n,body:s},response:Et(o),warnings:t,request:{body:JSON.stringify(e)}}}async doStream(r){let{args:e,warnings:t}=this.getArgs(r),n={...e,stream:true,stream_options:this.config.compatibility==="strict"?{include_usage:true}:void 0},{responseHeaders:o,value:s}=await(0, ze.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0, ze.combineHeaders)(this.config.headers(),r.headers),body:n,failedResponseHandler:ue,successfulResponseHandler:(0, ze.createEventSourceResponseHandler)(Hl),abortSignal:r.abortSignal,fetch:this.config.fetch}),{prompt:i,...a}=e,l="unknown",u={promptTokens:Number.NaN,completionTokens:Number.NaN},c,p=true;return {stream:s.pipeThrough(new TransformStream({transform(g,m){if(!g.success){l="error",m.enqueue({type:"error",error:g.error});return}let v=g.value;if("error"in v){l="error",m.enqueue({type:"error",error:v.error});return}p&&(p=false,m.enqueue({type:"response-metadata",...Et(v)})),v.usage!=null&&(u={promptTokens:v.usage.prompt_tokens,completionTokens:v.usage.completion_tokens});let f=v.choices[0];f?.finish_reason!=null&&(l=Pt(f.finish_reason)),f?.text!=null&&m.enqueue({type:"text-delta",textDelta:f.text});let d=xo(f?.logprobs);d?.length&&(c===void 0&&(c=[]),c.push(...d));},flush(g){g.enqueue({type:"finish",finishReason:l,logprobs:c,usage:u});}})),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:o},warnings:t,request:{body:JSON.stringify(n)}}}},Dl=j.z.object({id:j.z.string().nullish(),created:j.z.number().nullish(),model:j.z.string().nullish(),choices:j.z.array(j.z.object({text:j.z.string(),finish_reason:j.z.string(),logprobs:j.z.object({tokens:j.z.array(j.z.string()),token_logprobs:j.z.array(j.z.number()),top_logprobs:j.z.array(j.z.record(j.z.string(),j.z.number())).nullable()}).nullish()})),usage:j.z.object({prompt_tokens:j.z.number(),completion_tokens:j.z.number()})}),Hl=j.z.union([j.z.object({id:j.z.string().nullish(),created:j.z.number().nullish(),model:j.z.string().nullish(),choices:j.z.array(j.z.object({text:j.z.string(),finish_reason:j.z.string().nullish(),index:j.z.number(),logprobs:j.z.object({tokens:j.z.array(j.z.string()),token_logprobs:j.z.array(j.z.number()),top_logprobs:j.z.array(j.z.record(j.z.string(),j.z.number())).nullable()}).nullish()})),usage:j.z.object({prompt_tokens:j.z.number(),completion_tokens:j.z.number()}).nullish()}),fr]),Ll=L(),cr=V(),Ee=U("zod"),ql=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var r;return (r=this.settings.maxEmbeddingsPerCall)!=null?r:2048}get supportsParallelCalls(){var r;return (r=this.settings.supportsParallelCalls)!=null?r:true}async doEmbed({values:r,headers:e,abortSignal:t}){if(r.length>this.maxEmbeddingsPerCall)throw new Ll.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:r});let{responseHeaders:n,value:o}=await(0, cr.postJsonToApi)({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:(0, cr.combineHeaders)(this.config.headers(),e),body:{model:this.modelId,input:r,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:ue,successfulResponseHandler:(0, cr.createJsonResponseHandler)(Fl),abortSignal:t,fetch:this.config.fetch});return {embeddings:o.data.map(s=>s.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,rawResponse:{headers:n}}}},Fl=Ee.z.object({data:Ee.z.array(Ee.z.object({embedding:Ee.z.array(Ee.z.number())})),usage:Ee.z.object({prompt_tokens:Ee.z.number()}).nullish()}),dr=V(),Ct=U("zod"),Ul={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Bl=new Set(["gpt-image-1"]),Wl=class{constructor(r,e,t){this.modelId=r,this.settings=e,this.config=t,this.specificationVersion="v1";}get maxImagesPerCall(){var r,e;return (e=(r=this.settings.maxImagesPerCall)!=null?r:Ul[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:r,n:e,size:t,aspectRatio:n,seed:o,providerOptions:s,headers:i,abortSignal:a}){var l,u,c,p;let g=[];n!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&g.push({type:"unsupported-setting",setting:"seed"});let m=(c=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?c:new Date,{value:v,responseHeaders:f}=await(0, dr.postJsonToApi)({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:(0, dr.combineHeaders)(this.config.headers(),i),body:{model:this.modelId,prompt:r,n:e,size:t,...(p=s.openai)!=null?p:{},...Bl.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ue,successfulResponseHandler:(0, dr.createJsonResponseHandler)(Jl),abortSignal:a,fetch:this.config.fetch});return {images:v.data.map(d=>d.b64_json),warnings:g,response:{timestamp:m,modelId:this.modelId,headers:f}}}},Jl=Ct.z.object({data:Ct.z.array(Ct.z.object({b64_json:Ct.z.string()}))}),Ye=V(),K=U("zod"),Vl=K.z.object({include:K.z.array(K.z.string()).nullish(),language:K.z.string().nullish(),prompt:K.z.string().nullish(),temperature:K.z.number().min(0).max(1).nullish().default(0),timestampGranularities:K.z.array(K.z.enum(["word","segment"])).nullish().default(["segment"])}),ko={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Kl=class{constructor(r,e){this.modelId=r,this.config=e,this.specificationVersion="v1";}get provider(){return this.config.provider}getArgs({audio:r,mediaType:e,providerOptions:t}){var n,o,s,i,a;let l=[],u=(0, Ye.parseProviderOptions)({provider:"openai",providerOptions:t,schema:Vl}),c=new FormData,p=r instanceof Uint8Array?new Blob([r]):new Blob([(0, Ye.convertBase64ToUint8Array)(r)]);if(c.append("model",this.modelId),c.append("file",new File([p],"audio",{type:e})),u){let g={include:(n=u.include)!=null?n:void 0,language:(o=u.language)!=null?o:void 0,prompt:(s=u.prompt)!=null?s:void 0,temperature:(i=u.temperature)!=null?i:void 0,timestamp_granularities:(a=u.timestampGranularities)!=null?a:void 0};for(let m in g){let v=g[m];v!==void 0&&c.append(m,String(v));}}return {formData:c,warnings:l}}async doGenerate(r){var e,t,n,o,s,i;let a=(n=(t=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:t.call(e))!=null?n:new Date,{formData:l,warnings:u}=this.getArgs(r),{value:c,responseHeaders:p,rawValue:g}=await(0, Ye.postFormDataToApi)({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:(0, Ye.combineHeaders)(this.config.headers(),r.headers),formData:l,failedResponseHandler:ue,successfulResponseHandler:(0, Ye.createJsonResponseHandler)(Gl),abortSignal:r.abortSignal,fetch:this.config.fetch}),m=c.language!=null&&c.language in ko?ko[c.language]:void 0;return {text:c.text,segments:(s=(o=c.words)==null?void 0:o.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?s:[],language:m,durationInSeconds:(i=c.duration)!=null?i:void 0,warnings:u,response:{timestamp:a,modelId:this.modelId,headers:p,body:g}}}},Gl=K.z.object({text:K.z.string(),language:K.z.string().nullish(),duration:K.z.number().nullish(),words:K.z.array(K.z.object({word:K.z.string(),start:K.z.number(),end:K.z.number()})).nullish()}),Xl=L(),he=V(),b=U("zod"),Ro=L(),Yl=V();function Ql({prompt:r,systemMessageMode:e}){let t=[],n=[];for(let{role:o,content:s}of r)switch(o){case "system":{switch(e){case "system":{t.push({role:"system",content:s});break}case "developer":{t.push({role:"developer",content:s});break}case "remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{let i=e;throw new Error(`Unsupported system message mode: ${i}`)}}break}case "user":{t.push({role:"user",content:s.map((i,a)=>{var l,u,c,p;switch(i.type){case "text":return {type:"input_text",text:i.text};case "image":return {type:"input_image",image_url:i.image instanceof URL?i.image.toString():`data:${(l=i.mimeType)!=null?l:"image/jpeg"};base64,${(0, Yl.convertUint8ArrayToBase64)(i.image)}`,detail:(c=(u=i.providerMetadata)==null?void 0:u.openai)==null?void 0:c.imageDetail};case "file":{if(i.data instanceof URL)throw new Ro.UnsupportedFunctionalityError({functionality:"File URLs in user messages"});if(i.mimeType==="application/pdf")return {type:"input_file",filename:(p=i.filename)!=null?p:`part-${a}.pdf`,file_data:`data:application/pdf;base64,${i.data}`};throw new Ro.UnsupportedFunctionalityError({functionality:"Only PDF files are supported in user messages"})}}})});break}case "assistant":{for(let i of s)switch(i.type){case "text":{t.push({role:"assistant",content:[{type:"output_text",text:i.text}]});break}case "tool-call":{t.push({type:"function_call",call_id:i.toolCallId,name:i.toolName,arguments:JSON.stringify(i.args)});break}}break}case "tool":{for(let i of s)t.push({type:"function_call_output",call_id:i.toolCallId,output:JSON.stringify(i.result)});break}default:{let i=o;throw new Error(`Unsupported role: ${i}`)}}return {messages:t,warnings:n}}function Co({finishReason:r,hasToolCalls:e}){switch(r){case void 0:case null:return e?"tool-calls":"stop";case "max_output_tokens":return "length";case "content_filter":return "content-filter";default:return e?"tool-calls":"unknown"}}var Zl=L();function eu({mode:r,strict:e}){var t;let n=(t=r.tools)!=null&&t.length?r.tools:void 0,o=[];if(n==null)return {tools:void 0,tool_choice:void 0,toolWarnings:o};let s=r.toolChoice,i=[];for(let l of n)switch(l.type){case "function":i.push({type:"function",name:l.name,description:l.description,parameters:l.parameters,strict:e?true:void 0});break;case "provider-defined":l.id==="openai.web_search_preview"?i.push({type:"web_search_preview",search_context_size:l.args.searchContextSize,user_location:l.args.userLocation}):o.push({type:"unsupported-tool",tool:l});break;default:o.push({type:"unsupported-tool",tool:l});break}if(s==null)return {tools:i,tool_choice:void 0,toolWarnings:o};let a=s.type;switch(a){case "auto":case "none":case "required":return {tools:i,tool_choice:a,toolWarnings:o};case "tool":return s.toolName==="web_search_preview"?{tools:i,tool_choice:{type:"web_search_preview"},toolWarnings:o}:{tools:i,tool_choice:{type:"function",name:s.toolName},toolWarnings:o};default:{let l=a;throw new Zl.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${l}`})}}}var tu=class{constructor(r,e){this.specificationVersion="v1",this.defaultObjectGenerationMode="json",this.supportsStructuredOutputs=true,this.modelId=r,this.config=e;}get provider(){return this.config.provider}getArgs({mode:r,maxTokens:e,temperature:t,stopSequences:n,topP:o,topK:s,presencePenalty:i,frequencyPenalty:a,seed:l,prompt:u,providerMetadata:c,responseFormat:p}){var g,m,v;let f=[],d=_u(this.modelId),h=r.type;s!=null&&f.push({type:"unsupported-setting",setting:"topK"}),l!=null&&f.push({type:"unsupported-setting",setting:"seed"}),i!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&f.push({type:"unsupported-setting",setting:"stopSequences"});let{messages:_,warnings:C}=Ql({prompt:u,systemMessageMode:d.systemMessageMode});f.push(...C);let w=(0, he.parseProviderOptions)({provider:"openai",providerOptions:c,schema:xu}),x=(g=w?.strictSchemas)!=null?g:true,S={model:this.modelId,input:_,temperature:t,top_p:o,max_output_tokens:e,...p?.type==="json"&&{text:{format:p.schema!=null?{type:"json_schema",strict:x,name:(m=p.name)!=null?m:"response",description:p.description,schema:p.schema}:{type:"json_object"}}},metadata:w?.metadata,parallel_tool_calls:w?.parallelToolCalls,previous_response_id:w?.previousResponseId,store:w?.store,user:w?.user,instructions:w?.instructions,...d.isReasoningModel&&(w?.reasoningEffort!=null||w?.reasoningSummary!=null)&&{reasoning:{...w?.reasoningEffort!=null&&{effort:w.reasoningEffort},...w?.reasoningSummary!=null&&{summary:w.reasoningSummary}}},...d.requiredAutoTruncation};switch(d.isReasoningModel&&(S.temperature!=null&&(S.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))),h){case "regular":{let{tools:z,tool_choice:T,toolWarnings:k}=eu({mode:r,strict:x});return {args:{...S,tools:z,tool_choice:T},warnings:[...f,...k]}}case "object-json":return {args:{...S,text:{format:r.schema!=null?{type:"json_schema",strict:x,name:(v=r.name)!=null?v:"response",description:r.description,schema:r.schema}:{type:"json_object"}}},warnings:f};case "object-tool":return {args:{...S,tool_choice:{type:"function",name:r.tool.name},tools:[{type:"function",name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters,strict:x}]},warnings:f};default:{let z=h;throw new Error(`Unsupported type: ${z}`)}}}async doGenerate(r){var e,t,n,o,s,i,a;let{args:l,warnings:u}=this.getArgs(r),c=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:p,value:g,rawValue:m}=await(0, he.postJsonToApi)({url:c,headers:(0, he.combineHeaders)(this.config.headers(),r.headers),body:l,failedResponseHandler:ue,successfulResponseHandler:(0, he.createJsonResponseHandler)(b.z.object({id:b.z.string(),created_at:b.z.number(),error:b.z.object({message:b.z.string(),code:b.z.string()}).nullish(),model:b.z.string(),output:b.z.array(b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("message"),role:b.z.literal("assistant"),content:b.z.array(b.z.object({type:b.z.literal("output_text"),text:b.z.string(),annotations:b.z.array(b.z.object({type:b.z.literal("url_citation"),start_index:b.z.number(),end_index:b.z.number(),url:b.z.string(),title:b.z.string()}))}))}),b.z.object({type:b.z.literal("function_call"),call_id:b.z.string(),name:b.z.string(),arguments:b.z.string()}),b.z.object({type:b.z.literal("web_search_call")}),b.z.object({type:b.z.literal("computer_call")}),b.z.object({type:b.z.literal("reasoning"),summary:b.z.array(b.z.object({type:b.z.literal("summary_text"),text:b.z.string()}))})])),incomplete_details:b.z.object({reason:b.z.string()}).nullable(),usage:Eo})),abortSignal:r.abortSignal,fetch:this.config.fetch});if(g.error)throw new Xl.APICallError({message:g.error.message,url:c,requestBodyValues:l,statusCode:400,responseHeaders:p,responseBody:m,isRetryable:false});let v=g.output.filter(h=>h.type==="message").flatMap(h=>h.content).filter(h=>h.type==="output_text"),f=g.output.filter(h=>h.type==="function_call").map(h=>({toolCallType:"function",toolCallId:h.call_id,toolName:h.name,args:h.arguments})),d=(t=(e=g.output.find(h=>h.type==="reasoning"))==null?void 0:e.summary)!=null?t:null;return {text:v.map(h=>h.text).join(`
33
- `),sources:v.flatMap(h=>h.annotations.map(_=>{var C,w,x;return {sourceType:"url",id:(x=(w=(C=this.config).generateId)==null?void 0:w.call(C))!=null?x:(0, he.generateId)(),url:_.url,title:_.title}})),finishReason:Co({finishReason:(n=g.incomplete_details)==null?void 0:n.reason,hasToolCalls:f.length>0}),toolCalls:f.length>0?f:void 0,reasoning:d?d.map(h=>({type:"text",text:h.text})):void 0,usage:{promptTokens:g.usage.input_tokens,completionTokens:g.usage.output_tokens},rawCall:{rawPrompt:void 0,rawSettings:{}},rawResponse:{headers:p,body:m},request:{body:JSON.stringify(l)},response:{id:g.id,timestamp:new Date(g.created_at*1e3),modelId:g.model},providerMetadata:{openai:{responseId:g.id,cachedPromptTokens:(s=(o=g.usage.input_tokens_details)==null?void 0:o.cached_tokens)!=null?s:null,reasoningTokens:(a=(i=g.usage.output_tokens_details)==null?void 0:i.reasoning_tokens)!=null?a:null}},warnings:u}}async doStream(r){let{args:e,warnings:t}=this.getArgs(r),{responseHeaders:n,value:o}=await(0, he.postJsonToApi)({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:(0, he.combineHeaders)(this.config.headers(),r.headers),body:{...e,stream:true},failedResponseHandler:ue,successfulResponseHandler:(0, he.createEventSourceResponseHandler)(du),abortSignal:r.abortSignal,fetch:this.config.fetch}),s=this,i="unknown",a=NaN,l=NaN,u=null,c=null,p=null,g={},m=false;return {stream:o.pipeThrough(new TransformStream({transform(v,f){var d,h,_,C,w,x,S,z;if(!v.success){i="error",f.enqueue({type:"error",error:v.error});return}let T=v.value;if(yu(T))T.item.type==="function_call"&&(g[T.output_index]={toolName:T.item.name,toolCallId:T.item.call_id},f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:T.item.call_id,toolName:T.item.name,argsTextDelta:T.item.arguments}));else if(hu(T)){let k=g[T.output_index];k!=null&&f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:k.toolCallId,toolName:k.toolName,argsTextDelta:T.delta});}else fu(T)?(p=T.response.id,f.enqueue({type:"response-metadata",id:T.response.id,timestamp:new Date(T.response.created_at*1e3),modelId:T.response.model})):pu(T)?f.enqueue({type:"text-delta",textDelta:T.delta}):wu(T)?f.enqueue({type:"reasoning",textDelta:T.delta}):gu(T)&&T.item.type==="function_call"?(g[T.output_index]=void 0,m=true,f.enqueue({type:"tool-call",toolCallType:"function",toolCallId:T.item.call_id,toolName:T.item.name,args:T.item.arguments})):mu(T)?(i=Co({finishReason:(d=T.response.incomplete_details)==null?void 0:d.reason,hasToolCalls:m}),a=T.response.usage.input_tokens,l=T.response.usage.output_tokens,u=(_=(h=T.response.usage.input_tokens_details)==null?void 0:h.cached_tokens)!=null?_:u,c=(w=(C=T.response.usage.output_tokens_details)==null?void 0:C.reasoning_tokens)!=null?w:c):vu(T)?f.enqueue({type:"source",source:{sourceType:"url",id:(z=(S=(x=s.config).generateId)==null?void 0:S.call(x))!=null?z:(0, he.generateId)(),url:T.annotation.url,title:T.annotation.title}}):bu(T)&&f.enqueue({type:"error",error:T});},flush(v){v.enqueue({type:"finish",finishReason:i,usage:{promptTokens:a,completionTokens:l},...(u!=null||c!=null)&&{providerMetadata:{openai:{responseId:p,cachedPromptTokens:u,reasoningTokens:c}}}});}})),rawCall:{rawPrompt:void 0,rawSettings:{}},rawResponse:{headers:n},request:{body:JSON.stringify(e)},warnings:t}}},Eo=b.z.object({input_tokens:b.z.number(),input_tokens_details:b.z.object({cached_tokens:b.z.number().nullish()}).nullish(),output_tokens:b.z.number(),output_tokens_details:b.z.object({reasoning_tokens:b.z.number().nullish()}).nullish()}),ru=b.z.object({type:b.z.literal("response.output_text.delta"),delta:b.z.string()}),nu=b.z.object({type:b.z.enum(["response.completed","response.incomplete"]),response:b.z.object({incomplete_details:b.z.object({reason:b.z.string()}).nullish(),usage:Eo})}),ou=b.z.object({type:b.z.literal("response.created"),response:b.z.object({id:b.z.string(),created_at:b.z.number(),model:b.z.string()})}),su=b.z.object({type:b.z.literal("response.output_item.done"),output_index:b.z.number(),item:b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("message")}),b.z.object({type:b.z.literal("function_call"),id:b.z.string(),call_id:b.z.string(),name:b.z.string(),arguments:b.z.string(),status:b.z.literal("completed")})])}),iu=b.z.object({type:b.z.literal("response.function_call_arguments.delta"),item_id:b.z.string(),output_index:b.z.number(),delta:b.z.string()}),au=b.z.object({type:b.z.literal("response.output_item.added"),output_index:b.z.number(),item:b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("message")}),b.z.object({type:b.z.literal("function_call"),id:b.z.string(),call_id:b.z.string(),name:b.z.string(),arguments:b.z.string()})])}),lu=b.z.object({type:b.z.literal("response.output_text.annotation.added"),annotation:b.z.object({type:b.z.literal("url_citation"),url:b.z.string(),title:b.z.string()})}),uu=b.z.object({type:b.z.literal("response.reasoning_summary_text.delta"),item_id:b.z.string(),output_index:b.z.number(),summary_index:b.z.number(),delta:b.z.string()}),cu=b.z.object({type:b.z.literal("error"),code:b.z.string(),message:b.z.string(),param:b.z.string().nullish(),sequence_number:b.z.number()}),du=b.z.union([ru,nu,ou,su,iu,au,lu,uu,cu,b.z.object({type:b.z.string()}).passthrough()]);function pu(r){return r.type==="response.output_text.delta"}function gu(r){return r.type==="response.output_item.done"}function mu(r){return r.type==="response.completed"||r.type==="response.incomplete"}function fu(r){return r.type==="response.created"}function hu(r){return r.type==="response.function_call_arguments.delta"}function yu(r){return r.type==="response.output_item.added"}function vu(r){return r.type==="response.output_text.annotation.added"}function wu(r){return r.type==="response.reasoning_summary_text.delta"}function bu(r){return r.type==="error"}function _u(r){return r.startsWith("o")||r.startsWith("gpt-5")?r.startsWith("o1-mini")||r.startsWith("o1-preview")?{isReasoningModel:true,systemMessageMode:"remove",requiredAutoTruncation:false}:{isReasoningModel:true,systemMessageMode:"developer",requiredAutoTruncation:false}:{isReasoningModel:false,systemMessageMode:"system",requiredAutoTruncation:false}}var xu=b.z.object({metadata:b.z.any().nullish(),parallelToolCalls:b.z.boolean().nullish(),previousResponseId:b.z.string().nullish(),store:b.z.boolean().nullish(),user:b.z.string().nullish(),reasoningEffort:b.z.string().nullish(),strictSchemas:b.z.boolean().nullish(),instructions:b.z.string().nullish(),reasoningSummary:b.z.string().nullish()}),ku=U("zod"),Ru=ku.z.object({});function Cu({searchContextSize:r,userLocation:e}={}){return {type:"provider-defined",id:"openai.web_search_preview",args:{searchContextSize:r,userLocation:e},parameters:Ru}}var Tu={webSearchPreview:Cu},Tt=V(),pr=U("zod"),Pu=pr.z.object({instructions:pr.z.string().nullish(),speed:pr.z.number().min(.25).max(4).default(1).nullish()}),Eu=class{constructor(r,e){this.modelId=r,this.config=e,this.specificationVersion="v1";}get provider(){return this.config.provider}getArgs({text:r,voice:e="alloy",outputFormat:t="mp3",speed:n,instructions:o,providerOptions:s}){let i=[],a=(0, Tt.parseProviderOptions)({provider:"openai",providerOptions:s,schema:Pu}),l={model:this.modelId,input:r,voice:e,response_format:"mp3",speed:n,instructions:o};if(t&&(["mp3","opus","aac","flac","wav","pcm"].includes(t)?l.response_format=t:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${t}. Using mp3 instead.`})),a){let u={};for(let c in u){let p=u[c];p!==void 0&&(l[c]=p);}}return {requestBody:l,warnings:i}}async doGenerate(r){var e,t,n;let o=(n=(t=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:t.call(e))!=null?n:new Date,{requestBody:s,warnings:i}=this.getArgs(r),{value:a,responseHeaders:l,rawValue:u}=await(0, Tt.postJsonToApi)({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:(0, Tt.combineHeaders)(this.config.headers(),r.headers),body:s,failedResponseHandler:ue,successfulResponseHandler:(0, Tt.createBinaryResponseHandler)(),abortSignal:r.abortSignal,fetch:this.config.fetch});return {audio:a,warnings:i,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}};function Ao(r={}){var e,t,n;let o=(e=(0, wo.withoutTrailingSlash)(r.baseURL))!=null?e:"https://api.openai.com/v1",s=(t=r.compatibility)!=null?t:"compatible",i=(n=r.name)!=null?n:"openai",a=()=>({Authorization:`Bearer ${(0, wo.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":r.organization,"OpenAI-Project":r.project,...r.headers}),l=(h,_={})=>new Sl(h,_,{provider:`${i}.chat`,url:({path:C})=>`${o}${C}`,headers:a,compatibility:s,fetch:r.fetch}),u=(h,_={})=>new $l(h,_,{provider:`${i}.completion`,url:({path:C})=>`${o}${C}`,headers:a,compatibility:s,fetch:r.fetch}),c=(h,_={})=>new ql(h,_,{provider:`${i}.embedding`,url:({path:C})=>`${o}${C}`,headers:a,fetch:r.fetch}),p=(h,_={})=>new Wl(h,_,{provider:`${i}.image`,url:({path:C})=>`${o}${C}`,headers:a,fetch:r.fetch}),g=h=>new Kl(h,{provider:`${i}.transcription`,url:({path:_})=>`${o}${_}`,headers:a,fetch:r.fetch}),m=h=>new Eu(h,{provider:`${i}.speech`,url:({path:_})=>`${o}${_}`,headers:a,fetch:r.fetch}),v=(h,_)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h==="gpt-3.5-turbo-instruct"?u(h,_):l(h,_)},f=h=>new tu(h,{provider:`${i}.responses`,url:({path:_})=>`${o}${_}`,headers:a,fetch:r.fetch}),d=function(h,_){return v(h,_)};return d.languageModel=v,d.chat=l,d.completion=u,d.responses=f,d.embedding=c,d.textEmbedding=c,d.textEmbeddingModel=c,d.image=p,d.imageModel=p,d.transcription=g,d.transcriptionModel=g,d.speech=m,d.speechModel=m,d.tools=Tu,d}var Au=Ao({compatibility:"strict"});});var Ho=_e((Vm,Do)=>{y();var yr=Object.defineProperty,Su=Object.getOwnPropertyDescriptor,Iu=Object.getOwnPropertyNames,Ou=Object.prototype.hasOwnProperty,zu=(r,e)=>{for(var t in e)yr(r,t,{get:e[t],enumerable:true});},Mu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Iu(e))!Ou.call(r,o)&&o!==t&&yr(r,o,{get:()=>e[o],enumerable:!(n=Su(e,o))||n.enumerable});return r},ju=r=>Mu(yr({},"__esModule",{value:true}),r),No={};zu(No,{anthropic:()=>ac,createAnthropic:()=>$o});Do.exports=ju(No);var Nu=L(),Io=V(),Oo=L(),Ae=V(),R=U("zod"),$u=V(),Qe=U("zod"),Du=Qe.z.object({type:Qe.z.literal("error"),error:Qe.z.object({type:Qe.z.string(),message:Qe.z.string()})}),zo=(0, $u.createJsonErrorResponseHandler)({errorSchema:Du,errorToMessage:r=>r.error.message}),Hu=L();function Lu(r){var e;let t=(e=r.tools)!=null&&e.length?r.tools:void 0,n=[],o=new Set;if(t==null)return {tools:void 0,tool_choice:void 0,toolWarnings:n,betas:o};let s=[];for(let l of t)switch(l.type){case "function":s.push({name:l.name,description:l.description,input_schema:l.parameters});break;case "provider-defined":switch(l.id){case "anthropic.computer_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"computer_20250124",display_width_px:l.args.displayWidthPx,display_height_px:l.args.displayHeightPx,display_number:l.args.displayNumber});break;case "anthropic.computer_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"computer_20241022",display_width_px:l.args.displayWidthPx,display_height_px:l.args.displayHeightPx,display_number:l.args.displayNumber});break;case "anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"text_editor_20250124"});break;case "anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"text_editor_20241022"});break;case "anthropic.bash_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"bash_20250124"});break;case "anthropic.bash_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"bash_20241022"});break;default:n.push({type:"unsupported-tool",tool:l});break}break;default:n.push({type:"unsupported-tool",tool:l});break}let i=r.toolChoice;if(i==null)return {tools:s,tool_choice:void 0,toolWarnings:n,betas:o};let a=i.type;switch(a){case "auto":return {tools:s,tool_choice:{type:"auto"},toolWarnings:n,betas:o};case "required":return {tools:s,tool_choice:{type:"any"},toolWarnings:n,betas:o};case "none":return {tools:void 0,tool_choice:void 0,toolWarnings:n,betas:o};case "tool":return {tools:s,tool_choice:{type:"tool",name:i.toolName},toolWarnings:n,betas:o};default:{let l=a;throw new Hu.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${l}`})}}}var Mo=L(),qu=V();function Fu({prompt:r,sendReasoning:e,warnings:t}){var n,o,s,i;let a=new Set,l=Uu(r),u,c=[];function p(g){var m;let v=g?.anthropic;return (m=v?.cacheControl)!=null?m:v?.cache_control}for(let g=0;g<l.length;g++){let m=l[g],v=g===l.length-1,f=m.type;switch(f){case "system":{if(u!=null)throw new Mo.UnsupportedFunctionalityError({functionality:"Multiple system messages that are separated by user/assistant messages"});u=m.messages.map(({content:d,providerMetadata:h})=>({type:"text",text:d,cache_control:p(h)}));break}case "user":{let d=[];for(let h of m.messages){let{role:_,content:C}=h;switch(_){case "user":{for(let w=0;w<C.length;w++){let x=C[w],S=w===C.length-1,z=(n=p(x.providerMetadata))!=null?n:S?p(h.providerMetadata):void 0;switch(x.type){case "text":{d.push({type:"text",text:x.text,cache_control:z});break}case "image":{d.push({type:"image",source:x.image instanceof URL?{type:"url",url:x.image.toString()}:{type:"base64",media_type:(o=x.mimeType)!=null?o:"image/jpeg",data:(0, qu.convertUint8ArrayToBase64)(x.image)},cache_control:z});break}case "file":{if(x.mimeType!=="application/pdf")throw new Mo.UnsupportedFunctionalityError({functionality:"Non-PDF files in user messages"});a.add("pdfs-2024-09-25"),d.push({type:"document",source:x.data instanceof URL?{type:"url",url:x.data.toString()}:{type:"base64",media_type:"application/pdf",data:x.data},cache_control:z});break}}}break}case "tool":{for(let w=0;w<C.length;w++){let x=C[w],S=w===C.length-1,z=(s=p(x.providerMetadata))!=null?s:S?p(h.providerMetadata):void 0,T=x.content!=null?x.content.map(k=>{var O;switch(k.type){case "text":return {type:"text",text:k.text,cache_control:void 0};case "image":return {type:"image",source:{type:"base64",media_type:(O=k.mimeType)!=null?O:"image/jpeg",data:k.data},cache_control:void 0}}}):JSON.stringify(x.result);d.push({type:"tool_result",tool_use_id:x.toolCallId,content:T,is_error:x.isError,cache_control:z});}break}default:{let w=_;throw new Error(`Unsupported role: ${w}`)}}}c.push({role:"user",content:d});break}case "assistant":{let d=[];for(let h=0;h<m.messages.length;h++){let _=m.messages[h],C=h===m.messages.length-1,{content:w}=_;for(let x=0;x<w.length;x++){let S=w[x],z=x===w.length-1,T=(i=p(S.providerMetadata))!=null?i:z?p(_.providerMetadata):void 0;switch(S.type){case "text":{d.push({type:"text",text:v&&C&&z?S.text.trim():S.text,cache_control:T});break}case "reasoning":{e?d.push({type:"thinking",thinking:S.text,signature:S.signature,cache_control:T}):t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case "redacted-reasoning":{d.push({type:"redacted_thinking",data:S.data,cache_control:T});break}case "tool-call":{d.push({type:"tool_use",id:S.toolCallId,name:S.toolName,input:S.args,cache_control:T});break}}}}c.push({role:"assistant",content:d});break}default:{let d=f;throw new Error(`Unsupported type: ${d}`)}}}return {prompt:{system:u,messages:c},betas:a}}function Uu(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case "system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case "assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case "user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case "tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let s=o;throw new Error(`Unsupported role: ${s}`)}}}return e}function jo(r){switch(r){case "end_turn":case "stop_sequence":return "stop";case "tool_use":return "tool-calls";case "max_tokens":return "length";default:return "unknown"}}var Bu=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode="tool",this.modelId=r,this.settings=e,this.config=t;}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get supportsImageUrls(){return this.config.supportsImageUrls}async getArgs({mode:r,prompt:e,maxTokens:t=4096,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:c,providerMetadata:p}){var g,m,v;let f=r.type,d=[];i!=null&&d.push({type:"unsupported-setting",setting:"frequencyPenalty"}),a!=null&&d.push({type:"unsupported-setting",setting:"presencePenalty"}),c!=null&&d.push({type:"unsupported-setting",setting:"seed"}),u!=null&&u.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:h,betas:_}=Fu({prompt:e,sendReasoning:(g=this.settings.sendReasoning)!=null?g:true,warnings:d}),C=(0, Ae.parseProviderOptions)({provider:"anthropic",providerOptions:p,schema:Vu}),w=((m=C?.thinking)==null?void 0:m.type)==="enabled",x=(v=C?.thinking)==null?void 0:v.budgetTokens,S={model:this.modelId,max_tokens:t,temperature:n,top_k:s,top_p:o,stop_sequences:l,...w&&{thinking:{type:"enabled",budget_tokens:x}},system:h.system,messages:h.messages};if(w){if(x==null)throw new Oo.UnsupportedFunctionalityError({functionality:"thinking requires a budget"});S.temperature!=null&&(S.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),s!=null&&(S.top_k=void 0,d.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(S.top_p=void 0,d.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),S.max_tokens=t+x;}switch(f){case "regular":{let{tools:z,tool_choice:T,toolWarnings:k,betas:O}=Lu(r);return {args:{...S,tools:z,tool_choice:T},warnings:[...d,...k],betas:new Set([..._,...O])}}case "object-json":throw new Oo.UnsupportedFunctionalityError({functionality:"json-mode object generation"});case "object-tool":{let{name:z,description:T,parameters:k}=r.tool;return {args:{...S,tools:[{name:z,description:T,input_schema:k}],tool_choice:{type:"tool",name:z}},warnings:d,betas:_}}default:{let z=f;throw new Error(`Unsupported type: ${z}`)}}}async getHeaders({betas:r,headers:e}){return (0, Ae.combineHeaders)(await(0, Ae.resolve)(this.config.headers),r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{},e)}buildRequestUrl(r){var e,t,n;return (n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r){var e,t,n;return (n=(t=(e=this.config).transformRequestBody)==null?void 0:t.call(e,r))!=null?n:r}async doGenerate(r){var e,t,n,o;let{args:s,warnings:i,betas:a}=await this.getArgs(r),{responseHeaders:l,value:u,rawValue:c}=await(0, Ae.postJsonToApi)({url:this.buildRequestUrl(false),headers:await this.getHeaders({betas:a,headers:r.headers}),body:this.transformRequestBody(s),failedResponseHandler:zo,successfulResponseHandler:(0, Ae.createJsonResponseHandler)(Wu),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:p,...g}=s,m="";for(let d of u.content)d.type==="text"&&(m+=d.text);let v;if(u.content.some(d=>d.type==="tool_use")){v=[];for(let d of u.content)d.type==="tool_use"&&v.push({toolCallType:"function",toolCallId:d.id,toolName:d.name,args:JSON.stringify(d.input)});}let f=u.content.filter(d=>d.type==="redacted_thinking"||d.type==="thinking").map(d=>d.type==="thinking"?{type:"text",text:d.thinking,signature:d.signature}:{type:"redacted",data:d.data});return {text:m,reasoning:f.length>0?f:void 0,toolCalls:v,finishReason:jo(u.stop_reason),usage:{promptTokens:u.usage.input_tokens,completionTokens:u.usage.output_tokens},rawCall:{rawPrompt:p,rawSettings:g},rawResponse:{headers:l,body:c},response:{id:(e=u.id)!=null?e:void 0,modelId:(t=u.model)!=null?t:void 0},warnings:i,providerMetadata:{anthropic:{cacheCreationInputTokens:(n=u.usage.cache_creation_input_tokens)!=null?n:null,cacheReadInputTokens:(o=u.usage.cache_read_input_tokens)!=null?o:null}},request:{body:JSON.stringify(s)}}}async doStream(r){let{args:e,warnings:t,betas:n}=await this.getArgs(r),o={...e,stream:true},{responseHeaders:s,value:i}=await(0, Ae.postJsonToApi)({url:this.buildRequestUrl(true),headers:await this.getHeaders({betas:n,headers:r.headers}),body:this.transformRequestBody(o),failedResponseHandler:zo,successfulResponseHandler:(0, Ae.createEventSourceResponseHandler)(Ju),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:a,...l}=e,u="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},p={},g,m;return {stream:i.pipeThrough(new TransformStream({transform(v,f){var d,h,_,C;if(!v.success){f.enqueue({type:"error",error:v.error});return}let w=v.value;switch(w.type){case "ping":return;case "content_block_start":{let x=w.content_block.type;switch(m=x,x){case "text":case "thinking":return;case "redacted_thinking":{f.enqueue({type:"redacted-reasoning",data:w.content_block.data});return}case "tool_use":{p[w.index]={toolCallId:w.content_block.id,toolName:w.content_block.name,jsonText:""};return}default:{let S=x;throw new Error(`Unsupported content block type: ${S}`)}}}case "content_block_stop":{if(p[w.index]!=null){let x=p[w.index];f.enqueue({type:"tool-call",toolCallType:"function",toolCallId:x.toolCallId,toolName:x.toolName,args:x.jsonText}),delete p[w.index];}m=void 0;return}case "content_block_delta":{let x=w.delta.type;switch(x){case "text_delta":{f.enqueue({type:"text-delta",textDelta:w.delta.text});return}case "thinking_delta":{f.enqueue({type:"reasoning",textDelta:w.delta.thinking});return}case "signature_delta":{m==="thinking"&&f.enqueue({type:"reasoning-signature",signature:w.delta.signature});return}case "input_json_delta":{let S=p[w.index];f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:S.toolCallId,toolName:S.toolName,argsTextDelta:w.delta.partial_json}),S.jsonText+=w.delta.partial_json;return}default:{let S=x;throw new Error(`Unsupported delta type: ${S}`)}}}case "message_start":{c.promptTokens=w.message.usage.input_tokens,c.completionTokens=w.message.usage.output_tokens,g={anthropic:{cacheCreationInputTokens:(d=w.message.usage.cache_creation_input_tokens)!=null?d:null,cacheReadInputTokens:(h=w.message.usage.cache_read_input_tokens)!=null?h:null}},f.enqueue({type:"response-metadata",id:(_=w.message.id)!=null?_:void 0,modelId:(C=w.message.model)!=null?C:void 0});return}case "message_delta":{c.completionTokens=w.usage.output_tokens,u=jo(w.delta.stop_reason);return}case "message_stop":{f.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:g});return}case "error":{f.enqueue({type:"error",error:w.error});return}default:{let x=w;throw new Error(`Unsupported chunk type: ${x}`)}}}})),rawCall:{rawPrompt:a,rawSettings:l},rawResponse:{headers:s},warnings:t,request:{body:JSON.stringify(o)}}}},Wu=R.z.object({type:R.z.literal("message"),id:R.z.string().nullish(),model:R.z.string().nullish(),content:R.z.array(R.z.discriminatedUnion("type",[R.z.object({type:R.z.literal("text"),text:R.z.string()}),R.z.object({type:R.z.literal("thinking"),thinking:R.z.string(),signature:R.z.string()}),R.z.object({type:R.z.literal("redacted_thinking"),data:R.z.string()}),R.z.object({type:R.z.literal("tool_use"),id:R.z.string(),name:R.z.string(),input:R.z.unknown()})])),stop_reason:R.z.string().nullish(),usage:R.z.object({input_tokens:R.z.number(),output_tokens:R.z.number(),cache_creation_input_tokens:R.z.number().nullish(),cache_read_input_tokens:R.z.number().nullish()})}),Ju=R.z.discriminatedUnion("type",[R.z.object({type:R.z.literal("message_start"),message:R.z.object({id:R.z.string().nullish(),model:R.z.string().nullish(),usage:R.z.object({input_tokens:R.z.number(),output_tokens:R.z.number(),cache_creation_input_tokens:R.z.number().nullish(),cache_read_input_tokens:R.z.number().nullish()})})}),R.z.object({type:R.z.literal("content_block_start"),index:R.z.number(),content_block:R.z.discriminatedUnion("type",[R.z.object({type:R.z.literal("text"),text:R.z.string()}),R.z.object({type:R.z.literal("thinking"),thinking:R.z.string()}),R.z.object({type:R.z.literal("tool_use"),id:R.z.string(),name:R.z.string()}),R.z.object({type:R.z.literal("redacted_thinking"),data:R.z.string()})])}),R.z.object({type:R.z.literal("content_block_delta"),index:R.z.number(),delta:R.z.discriminatedUnion("type",[R.z.object({type:R.z.literal("input_json_delta"),partial_json:R.z.string()}),R.z.object({type:R.z.literal("text_delta"),text:R.z.string()}),R.z.object({type:R.z.literal("thinking_delta"),thinking:R.z.string()}),R.z.object({type:R.z.literal("signature_delta"),signature:R.z.string()})])}),R.z.object({type:R.z.literal("content_block_stop"),index:R.z.number()}),R.z.object({type:R.z.literal("error"),error:R.z.object({type:R.z.string(),message:R.z.string()})}),R.z.object({type:R.z.literal("message_delta"),delta:R.z.object({stop_reason:R.z.string().nullish()}),usage:R.z.object({output_tokens:R.z.number()})}),R.z.object({type:R.z.literal("message_stop")}),R.z.object({type:R.z.literal("ping")})]),Vu=R.z.object({thinking:R.z.object({type:R.z.union([R.z.literal("enabled"),R.z.literal("disabled")]),budgetTokens:R.z.number().optional()}).optional()}),N=U("zod"),Ku=N.z.object({command:N.z.string(),restart:N.z.boolean().optional()});function Gu(r={}){return {type:"provider-defined",id:"anthropic.bash_20241022",args:{},parameters:Ku,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var Xu=N.z.object({command:N.z.string(),restart:N.z.boolean().optional()});function Yu(r={}){return {type:"provider-defined",id:"anthropic.bash_20250124",args:{},parameters:Xu,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var Qu=N.z.object({command:N.z.enum(["view","create","str_replace","insert","undo_edit"]),path:N.z.string(),file_text:N.z.string().optional(),insert_line:N.z.number().int().optional(),new_str:N.z.string().optional(),old_str:N.z.string().optional(),view_range:N.z.array(N.z.number().int()).optional()});function Zu(r={}){return {type:"provider-defined",id:"anthropic.text_editor_20241022",args:{},parameters:Qu,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var ec=N.z.object({command:N.z.enum(["view","create","str_replace","insert","undo_edit"]),path:N.z.string(),file_text:N.z.string().optional(),insert_line:N.z.number().int().optional(),new_str:N.z.string().optional(),old_str:N.z.string().optional(),view_range:N.z.array(N.z.number().int()).optional()});function tc(r={}){return {type:"provider-defined",id:"anthropic.text_editor_20250124",args:{},parameters:ec,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var rc=N.z.object({action:N.z.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:N.z.array(N.z.number().int()).optional(),text:N.z.string().optional()});function nc(r){return {type:"provider-defined",id:"anthropic.computer_20241022",args:{displayWidthPx:r.displayWidthPx,displayHeightPx:r.displayHeightPx,displayNumber:r.displayNumber},parameters:rc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var oc=N.z.object({action:N.z.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:N.z.tuple([N.z.number().int(),N.z.number().int()]).optional(),duration:N.z.number().optional(),scroll_amount:N.z.number().optional(),scroll_direction:N.z.enum(["up","down","left","right"]).optional(),start_coordinate:N.z.tuple([N.z.number().int(),N.z.number().int()]).optional(),text:N.z.string().optional()});function sc(r){return {type:"provider-defined",id:"anthropic.computer_20250124",args:{displayWidthPx:r.displayWidthPx,displayHeightPx:r.displayHeightPx,displayNumber:r.displayNumber},parameters:oc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var ic={bash_20241022:Gu,bash_20250124:Yu,textEditor_20241022:Zu,textEditor_20250124:tc,computer_20241022:nc,computer_20250124:sc};function $o(r={}){var e;let t=(e=(0, Io.withoutTrailingSlash)(r.baseURL))!=null?e:"https://api.anthropic.com/v1",n=()=>({"anthropic-version":"2023-06-01","x-api-key":(0, Io.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...r.headers}),o=(i,a={})=>new Bu(i,a,{provider:"anthropic.messages",baseURL:t,headers:n,fetch:r.fetch,supportsImageUrls:true}),s=function(i,a){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(i,a)};return s.languageModel=o,s.chat=o,s.messages=o,s.textEmbeddingModel=i=>{throw new Nu.NoSuchModelError({modelId:i,modelType:"textEmbeddingModel"})},s.tools=ic,s}var ac=$o();});var Zo=_e((Xm,Qo)=>{y();var _r=Object.defineProperty,lc=Object.getOwnPropertyDescriptor,uc=Object.getOwnPropertyNames,cc=Object.prototype.hasOwnProperty,dc=(r,e)=>{for(var t in e)_r(r,t,{get:e[t],enumerable:true});},pc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of uc(e))!cc.call(r,o)&&o!==t&&_r(r,o,{get:()=>e[o],enumerable:!(n=lc(e,o))||n.enumerable});return r},gc=r=>pc(_r({},"__esModule",{value:true}),r),Vo={};dc(Vo,{createGoogleGenerativeAI:()=>Yo,google:()=>Sc});Qo.exports=gc(Vo);var vr=V(),ye=V(),P=U("zod");function ee(r){if(mc(r))return;if(typeof r=="boolean")return {type:"boolean",properties:{}};let{type:e,description:t,required:n,properties:o,items:s,allOf:i,anyOf:a,oneOf:l,format:u,const:c,minLength:p,enum:g}=r,m={};if(t&&(m.description=t),n&&(m.required=n),u&&(m.format=u),c!==void 0&&(m.enum=[c]),e&&(Array.isArray(e)?e.includes("null")?(m.type=e.filter(v=>v!=="null")[0],m.nullable=true):m.type=e:e==="null"?m.type="null":m.type=e),g!==void 0&&(m.enum=g),o!=null&&(m.properties=Object.entries(o).reduce((v,[f,d])=>(v[f]=ee(d),v),{})),s&&(m.items=Array.isArray(s)?s.map(ee):ee(s)),i&&(m.allOf=i.map(ee)),a)if(a.some(v=>typeof v=="object"&&v?.type==="null")){let v=a.filter(f=>!(typeof f=="object"&&f?.type==="null"));if(v.length===1){let f=ee(v[0]);typeof f=="object"&&(m.nullable=true,Object.assign(m,f));}else m.anyOf=v.map(ee),m.nullable=true;}else m.anyOf=a.map(ee);return l&&(m.oneOf=l.map(ee)),p!==void 0&&(m.minLength=p),m}function mc(r){return r!=null&&typeof r=="object"&&r.type==="object"&&(r.properties==null||Object.keys(r.properties).length===0)&&!r.additionalProperties}var wr=L(),fc=V();function hc(r){var e,t;let n=[],o=[],s=true;for(let{role:i,content:a}of r)switch(i){case "system":{if(!s)throw new wr.UnsupportedFunctionalityError({functionality:"system messages are only supported at the beginning of the conversation"});n.push({text:a});break}case "user":{s=false;let l=[];for(let u of a)switch(u.type){case "text":{l.push({text:u.text});break}case "image":{l.push(u.image instanceof URL?{fileData:{mimeType:(e=u.mimeType)!=null?e:"image/jpeg",fileUri:u.image.toString()}}:{inlineData:{mimeType:(t=u.mimeType)!=null?t:"image/jpeg",data:(0, fc.convertUint8ArrayToBase64)(u.image)}});break}case "file":{l.push(u.data instanceof URL?{fileData:{mimeType:u.mimeType,fileUri:u.data.toString()}}:{inlineData:{mimeType:u.mimeType,data:u.data}});break}}o.push({role:"user",parts:l});break}case "assistant":{s=false,o.push({role:"model",parts:a.map(l=>{switch(l.type){case "text":return l.text.length===0?void 0:{text:l.text};case "file":{if(l.mimeType!=="image/png")throw new wr.UnsupportedFunctionalityError({functionality:"Only PNG images are supported in assistant messages"});if(l.data instanceof URL)throw new wr.UnsupportedFunctionalityError({functionality:"File data URLs in assistant messages are not supported"});return {inlineData:{mimeType:l.mimeType,data:l.data}}}case "tool-call":return {functionCall:{name:l.toolName,args:l.args}}}}).filter(l=>l!==void 0)});break}case "tool":{s=false,o.push({role:"user",parts:a.map(l=>({functionResponse:{name:l.toolName,response:{name:l.toolName,content:l.result}}}))});break}}return {systemInstruction:n.length>0?{parts:n}:void 0,contents:o}}function Lo(r){return r.includes("/")?r:`models/${r}`}var yc=V(),Ze=U("zod"),vc=Ze.z.object({error:Ze.z.object({code:Ze.z.number().nullable(),message:Ze.z.string(),status:Ze.z.string()})}),br=(0, yc.createJsonErrorResponseHandler)({errorSchema:vc,errorToMessage:r=>r.error.message}),wc=L();function bc(r,e,t,n){var o,s;let i=(o=r.tools)!=null&&o.length?r.tools:void 0,a=[],l=n.includes("gemini-2"),u=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(e)return {tools:l?{googleSearch:{}}:{googleSearchRetrieval:!u||!t?{}:{dynamicRetrievalConfig:t}},toolConfig:void 0,toolWarnings:a};if(i==null)return {tools:void 0,toolConfig:void 0,toolWarnings:a};let c=[];for(let m of i)m.type==="provider-defined"?a.push({type:"unsupported-tool",tool:m}):c.push({name:m.name,description:(s=m.description)!=null?s:"",parameters:ee(m.parameters)});let p=r.toolChoice;if(p==null)return {tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:a};let g=p.type;switch(g){case "auto":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:a};case "none":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:a};case "required":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:a};case "tool":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[p.toolName]}},toolWarnings:a};default:{let m=g;throw new wc.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${m}`})}}}function qo({finishReason:r,hasToolCalls:e}){switch(r){case "STOP":return e?"tool-calls":"stop";case "MAX_TOKENS":return "length";case "IMAGE_SAFETY":case "RECITATION":case "SAFETY":case "BLOCKLIST":case "PROHIBITED_CONTENT":case "SPII":return "content-filter";case "FINISH_REASON_UNSPECIFIED":case "OTHER":return "other";case "MALFORMED_FUNCTION_CALL":return "error";default:return "unknown"}}var _c=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode="json",this.supportsImageUrls=false,this.modelId=r,this.settings=e,this.config=t;}get supportsStructuredOutputs(){var r;return (r=this.settings.structuredOutputs)!=null?r:true}get provider(){return this.config.provider}async getArgs({mode:r,prompt:e,maxTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:c,providerMetadata:p}){var g,m,v;let f=r.type,d=[],h=(0, ye.parseProviderOptions)({provider:"google",providerOptions:p,schema:Cc});((g=h?.thinkingConfig)==null?void 0:g.includeThoughts)===true&&!this.config.provider.startsWith("google.vertex.")&&d.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _={maxOutputTokens:t,temperature:n,topK:s,topP:o,frequencyPenalty:i,presencePenalty:a,stopSequences:l,seed:c,responseMimeType:u?.type==="json"?"application/json":void 0,responseSchema:u?.type==="json"&&u.schema!=null&&this.supportsStructuredOutputs?ee(u.schema):void 0,...this.settings.audioTimestamp&&{audioTimestamp:this.settings.audioTimestamp},responseModalities:h?.responseModalities,thinkingConfig:h?.thinkingConfig},{contents:C,systemInstruction:w}=hc(e);switch(f){case "regular":{let{tools:x,toolConfig:S,toolWarnings:z}=bc(r,(m=this.settings.useSearchGrounding)!=null?m:false,this.settings.dynamicRetrievalConfig,this.modelId);return {args:{generationConfig:_,contents:C,systemInstruction:w,safetySettings:this.settings.safetySettings,tools:x,toolConfig:S,cachedContent:this.settings.cachedContent},warnings:[...d,...z]}}case "object-json":return {args:{generationConfig:{..._,responseMimeType:"application/json",responseSchema:r.schema!=null&&this.supportsStructuredOutputs?ee(r.schema):void 0},contents:C,systemInstruction:w,safetySettings:this.settings.safetySettings,cachedContent:this.settings.cachedContent},warnings:d};case "object-tool":return {args:{generationConfig:_,contents:C,systemInstruction:w,tools:{functionDeclarations:[{name:r.tool.name,description:(v=r.tool.description)!=null?v:"",parameters:ee(r.tool.parameters)}]},toolConfig:{functionCallingConfig:{mode:"ANY"}},safetySettings:this.settings.safetySettings,cachedContent:this.settings.cachedContent},warnings:d};default:{let x=f;throw new Error(`Unsupported type: ${x}`)}}}supportsUrl(r){return this.config.isSupportedUrl(r)}async doGenerate(r){var e,t,n,o,s;let{args:i,warnings:a}=await this.getArgs(r),l=JSON.stringify(i),u=(0, ye.combineHeaders)(await(0, ye.resolve)(this.config.headers),r.headers),{responseHeaders:c,value:p,rawValue:g}=await(0, ye.postJsonToApi)({url:`${this.config.baseURL}/${Lo(this.modelId)}:generateContent`,headers:u,body:i,failedResponseHandler:br,successfulResponseHandler:(0, ye.createJsonResponseHandler)(kc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{contents:m,...v}=i,f=p.candidates[0],d=f.content==null||typeof f.content!="object"||!("parts"in f.content)?[]:f.content.parts,h=Fo({parts:d,generateId:this.config.generateId}),_=p.usageMetadata;return {text:Uo(d),reasoning:Bo(d),files:(e=Wo(d))==null?void 0:e.map(C=>({data:C.inlineData.data,mimeType:C.inlineData.mimeType})),toolCalls:h,finishReason:qo({finishReason:f.finishReason,hasToolCalls:h!=null&&h.length>0}),usage:{promptTokens:(t=_?.promptTokenCount)!=null?t:NaN,completionTokens:(n=_?.candidatesTokenCount)!=null?n:NaN},rawCall:{rawPrompt:m,rawSettings:v},rawResponse:{headers:c,body:g},warnings:a,providerMetadata:{google:{groundingMetadata:(o=f.groundingMetadata)!=null?o:null,safetyRatings:(s=f.safetyRatings)!=null?s:null}},sources:Jo({groundingMetadata:f.groundingMetadata,generateId:this.config.generateId}),request:{body:l}}}async doStream(r){let{args:e,warnings:t}=await this.getArgs(r),n=JSON.stringify(e),o=(0, ye.combineHeaders)(await(0, ye.resolve)(this.config.headers),r.headers),{responseHeaders:s,value:i}=await(0, ye.postJsonToApi)({url:`${this.config.baseURL}/${Lo(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:br,successfulResponseHandler:(0, ye.createEventSourceResponseHandler)(Rc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{contents:a,...l}=e,u="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},p,g=this.config.generateId,m=false;return {stream:i.pipeThrough(new TransformStream({transform(v,f){var d,h,_,C,w,x;if(!v.success){f.enqueue({type:"error",error:v.error});return}let S=v.value,z=S.usageMetadata;z!=null&&(c={promptTokens:(d=z.promptTokenCount)!=null?d:NaN,completionTokens:(h=z.candidatesTokenCount)!=null?h:NaN});let T=(_=S.candidates)==null?void 0:_[0];if(T==null)return;let k=T.content;if(k!=null){let O=Uo(k.parts);O!=null&&f.enqueue({type:"text-delta",textDelta:O});let I=Bo(k.parts);if(I!=null)for(let H of I)f.enqueue({type:"reasoning",textDelta:H.text});let W=Wo(k.parts);if(W!=null)for(let H of W)f.enqueue({type:"file",mimeType:H.inlineData.mimeType,data:H.inlineData.data});let G=Fo({parts:k.parts,generateId:g});if(G!=null)for(let H of G)f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:H.toolCallId,toolName:H.toolName,argsTextDelta:H.args}),f.enqueue({type:"tool-call",toolCallType:"function",toolCallId:H.toolCallId,toolName:H.toolName,args:H.args}),m=true;}if(T.finishReason!=null){u=qo({finishReason:T.finishReason,hasToolCalls:m});let O=(C=Jo({groundingMetadata:T.groundingMetadata,generateId:g}))!=null?C:[];for(let I of O)f.enqueue({type:"source",source:I});p={google:{groundingMetadata:(w=T.groundingMetadata)!=null?w:null,safetyRatings:(x=T.safetyRatings)!=null?x:null}};}},flush(v){v.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:p});}})),rawCall:{rawPrompt:a,rawSettings:l},rawResponse:{headers:s},warnings:t,request:{body:n}}}};function Fo({parts:r,generateId:e}){let t=r?.filter(n=>"functionCall"in n);return t==null||t.length===0?void 0:t.map(n=>({toolCallType:"function",toolCallId:e(),toolName:n.functionCall.name,args:JSON.stringify(n.functionCall.args)}))}function Uo(r){let e=r?.filter(t=>"text"in t&&t.thought!==true);return e==null||e.length===0?void 0:e.map(t=>t.text).join("")}function Bo(r){let e=r?.filter(t=>"text"in t&&t.thought===true&&t.text!=null);return e==null||e.length===0?void 0:e.map(t=>({type:"text",text:t.text}))}function Wo(r){return r?.filter(e=>"inlineData"in e)}function Jo({groundingMetadata:r,generateId:e}){var t;return (t=r?.groundingChunks)==null?void 0:t.filter(n=>n.web!=null).map(n=>({sourceType:"url",id:e(),url:n.web.uri,title:n.web.title}))}var Ko=P.z.object({parts:P.z.array(P.z.union([P.z.object({functionCall:P.z.object({name:P.z.string(),args:P.z.unknown()})}),P.z.object({inlineData:P.z.object({mimeType:P.z.string(),data:P.z.string()})}),P.z.object({text:P.z.string().nullish(),thought:P.z.boolean().nullish()})])).nullish()}),xc=P.z.object({web:P.z.object({uri:P.z.string(),title:P.z.string()}).nullish(),retrievedContext:P.z.object({uri:P.z.string(),title:P.z.string()}).nullish()}),Go=P.z.object({webSearchQueries:P.z.array(P.z.string()).nullish(),retrievalQueries:P.z.array(P.z.string()).nullish(),searchEntryPoint:P.z.object({renderedContent:P.z.string()}).nullish(),groundingChunks:P.z.array(xc).nullish(),groundingSupports:P.z.array(P.z.object({segment:P.z.object({startIndex:P.z.number().nullish(),endIndex:P.z.number().nullish(),text:P.z.string().nullish()}),segment_text:P.z.string().nullish(),groundingChunkIndices:P.z.array(P.z.number()).nullish(),supportChunkIndices:P.z.array(P.z.number()).nullish(),confidenceScores:P.z.array(P.z.number()).nullish(),confidenceScore:P.z.array(P.z.number()).nullish()})).nullish(),retrievalMetadata:P.z.union([P.z.object({webDynamicRetrievalScore:P.z.number()}),P.z.object({})]).nullish()}),Xo=P.z.object({category:P.z.string().nullish(),probability:P.z.string().nullish(),probabilityScore:P.z.number().nullish(),severity:P.z.string().nullish(),severityScore:P.z.number().nullish(),blocked:P.z.boolean().nullish()}),kc=P.z.object({candidates:P.z.array(P.z.object({content:Ko.nullish().or(P.z.object({}).strict()),finishReason:P.z.string().nullish(),safetyRatings:P.z.array(Xo).nullish(),groundingMetadata:Go.nullish()})),usageMetadata:P.z.object({promptTokenCount:P.z.number().nullish(),candidatesTokenCount:P.z.number().nullish(),totalTokenCount:P.z.number().nullish()}).nullish()}),Rc=P.z.object({candidates:P.z.array(P.z.object({content:Ko.nullish(),finishReason:P.z.string().nullish(),safetyRatings:P.z.array(Xo).nullish(),groundingMetadata:Go.nullish()})).nullish(),usageMetadata:P.z.object({promptTokenCount:P.z.number().nullish(),candidatesTokenCount:P.z.number().nullish(),totalTokenCount:P.z.number().nullish()}).nullish()}),Cc=P.z.object({responseModalities:P.z.array(P.z.enum(["TEXT","IMAGE"])).nullish(),thinkingConfig:P.z.object({thinkingBudget:P.z.number().nullish(),includeThoughts:P.z.boolean().nullish()}).nullish()}),Tc=L(),At=V(),et=U("zod"),Pc=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){return 2048}get supportsParallelCalls(){return true}async doEmbed({values:r,headers:e,abortSignal:t}){if(r.length>this.maxEmbeddingsPerCall)throw new Tc.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:r});let n=(0, At.combineHeaders)(await(0, At.resolve)(this.config.headers),e),{responseHeaders:o,value:s}=await(0, At.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:n,body:{requests:r.map(i=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:i}]},outputDimensionality:this.settings.outputDimensionality,taskType:this.settings.taskType}))},failedResponseHandler:br,successfulResponseHandler:(0, At.createJsonResponseHandler)(Ec),abortSignal:t,fetch:this.config.fetch});return {embeddings:s.embeddings.map(i=>i.values),usage:void 0,rawResponse:{headers:o}}}},Ec=et.z.object({embeddings:et.z.array(et.z.object({values:et.z.array(et.z.number())}))});function Ac(r){return r.toString().startsWith("https://generativelanguage.googleapis.com/v1beta/files/")}function Yo(r={}){var e;let t=(e=(0, vr.withoutTrailingSlash)(r.baseURL))!=null?e:"https://generativelanguage.googleapis.com/v1beta",n=()=>({"x-goog-api-key":(0, vr.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...r.headers}),o=(a,l={})=>{var u;return new _c(a,l,{provider:"google.generative-ai",baseURL:t,headers:n,generateId:(u=r.generateId)!=null?u:vr.generateId,isSupportedUrl:Ac,fetch:r.fetch})},s=(a,l={})=>new Pc(a,l,{provider:"google.generative-ai",baseURL:t,headers:n,fetch:r.fetch}),i=function(a,l){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return o(a,l)};return i.languageModel=o,i.chat=o,i.generativeAI=o,i.embedding=s,i.textEmbedding=s,i.textEmbeddingModel=s,i}var Sc=Yo();});var es,ts;exports.VercelProviderRuntime=void 0;var xr=oe(()=>{y();Re();es=10,ts=50,exports.VercelProviderRuntime=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,n){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(n?.tools??[],s),a=this.createModel(n?.model),l=Math.min(n?.maxSteps??this.config.maxSteps??es,ts);try{let u=0,c=await o({model:a,system:n?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:l,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:g=>{if(u++,!!n?.onOutput){if(g.toolCalls&&g.toolCalls.length>0)for(let m of g.toolCalls)n.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:m.toolCallId,name:m.toolName,input:m.args}]}}),"stdout");if(g.toolResults&&g.toolResults.length>0)for(let m of g.toolResults){let v=typeof m.result=="string"?m.result:JSON.stringify(m.result);n.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:m.toolCallId,output:v,is_error:!1}]}}),"stdout");}}}}),p=new Set((n?.tools??[]).filter(g=>!g.execute).map(g=>g.name));if(c.finishReason==="tool-calls"&&Array.isArray(c.toolCalls)&&c.toolCalls.length>0){let g=c.toolCalls.filter(m=>p.has(m.toolName));if(g.length>0){let m=g[0];throw new exports.ClientToolCallRequiredError({toolCallId:m.toolCallId,toolName:m.toolName,args:m.args},{userMessage:e,responseMessages:c.response?.messages??[],toolDefinitions:n?.tools??[],maxSteps:l,systemPrompt:n?.systemPrompt,modelOverride:n?.model})}}if(n?.onUsage&&c.usage){let g={inputTokens:c.usage.promptTokens??0,outputTokens:c.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};n.onUsage(g);}return n?.onModel&&n.onModel(n.model??this.config.model),c.text??""}catch(u){throw u instanceof exports.ClientToolCallRequiredError?u:u.status===401?new exports.ProviderError(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):u.status===429?new exports.ProviderError(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new exports.ProviderError(`Provider error: ${u.message}`,this.config.provider)}}async continueWithToolResults(e,t,n){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),l=Math.min(e.maxSteps??this.config.maxSteps??es,ts),u=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(c=>({type:"tool-result",toolCallId:c.toolCallId,toolName:c.toolName,result:typeof c.result=="string"?c.result:JSON.stringify(c.result)}))}];try{let c=await o({model:a,system:e.systemPrompt??void 0,messages:u,tools:i,maxSteps:l,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),p=new Set(e.toolDefinitions.filter(g=>!g.execute).map(g=>g.name));if(c.finishReason==="tool-calls"&&Array.isArray(c.toolCalls)&&c.toolCalls.length>0){let g=c.toolCalls.filter(m=>p.has(m.toolName));if(g.length>0){let m=g[0];throw new exports.ClientToolCallRequiredError({toolCallId:m.toolCallId,toolName:m.toolName,args:m.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(v=>({type:"tool-result",toolCallId:v.toolCallId,toolName:v.toolName,result:typeof v.result=="string"?v.result:JSON.stringify(v.result)}))},...c.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return n?.onUsage&&c.usage&&n.onUsage({inputTokens:c.usage.promptTokens??0,outputTokens:c.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),n?.onModel&&n.onModel(e.modelOverride??this.config.model),c.text??""}catch(c){throw c instanceof exports.ClientToolCallRequiredError?c:new exports.ProviderError(`Provider error: ${c.message}`,this.config.provider)}}convertTools(e,t){let{z:n}=U("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},n);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let n={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let l;switch(a.type){case "string":l=t.string();break;case "number":l=t.number();break;case "integer":l=t.number().int();break;case "boolean":l=t.boolean();break;case "array":l=t.array(t.any());break;default:l=t.any();}a.description&&(l=l.describe(a.description)),s.includes(i)||(l=l.optional()),n[i]=l;}return t.object(n)}createModel(e){let{provider:t,apiKey:n,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=hr();return i({apiKey:n||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=hr();return i({apiKey:n||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=Ho();return i({apiKey:n||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=Zo();return i({apiKey:n||process.env.GOOGLE_API_KEY})(s)}default:throw new exports.ProviderError(`Unsupported API provider: ${t}`,t)}}};});var ns={};zt(ns,{registerApiProviders:()=>rs});function rs(r){Ie("api",(e,t)=>{let n=r?.apiKeys?.[e];return new exports.VercelProviderRuntime({provider:t,model:"",apiKey:n,maxSteps:r?.defaults?.maxSteps,temperature:r?.defaults?.temperature})});}var kr=oe(()=>{y();Re();xr();});function Ic(r){if(!r)return r;let e=r.trim().replace(/\/+$/,"");return e.toLowerCase().endsWith("/mcp")?e.slice(0,-4):e}exports.McpHttpTransport=void 0;var Rr=oe(()=>{y();exports.McpHttpTransport=class{endpoint;headers;timeoutMs;constructor(e){let t=Ic(e.url);this.endpoint=`${t}/mcp`,this.headers={"Content-Type":"application/json",...e.headers??{}},e.apiKey&&(this.headers.Authorization=`Bearer ${e.apiKey}`),this.timeoutMs=e.timeoutMs??3e4;}async send(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{let o=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(e),signal:t.signal});if(clearTimeout(n),!o.ok){let a=await o.text();throw new Error(`HTTP ${o.status}: ${o.statusText}${a?` - ${a}`:""}`)}let s=o.headers.get("content-type");if(s?.includes("application/json"))return await o.json();let i=await o.text();return {jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Unexpected response content-type: ${s}`,data:i}}}catch(o){throw clearTimeout(n),o instanceof Error&&o.name==="AbortError"?new Error(`MCP-HTTP request timeout after ${this.timeoutMs}ms to ${this.endpoint}`):o}}async close(){}};});exports.RemoteAgentManager=void 0;var Cr=oe(()=>{y();Rr();exports.RemoteAgentManager=class{logger;configs=new Map;transports=new Map;constructor(e={}){this.logger=e.logger??(()=>{});}loadConfig(e,t){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,new exports.McpHttpTransport({url:t.url,apiKey:t.apiKey,headers:t.headers,timeoutMs:t.timeoutMs})),this.logger(`Loaded remote agent config for: ${e}`,"debug");}loadConfigWithTransport(e,t,n){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,n),this.logger(`Loaded remote agent config for: ${e} (custom transport)`,"debug");}getConfig(e){return this.configs.get(e)}isRemoteAgent(e){return this.configs.has(e)}getRemoteAgentIds(){return Array.from(this.configs.keys())}async query(e,t){let n=this.requireConfig(e),o=n.tools?.query??"crewx_queryAgent",i={agentId:n.agentId??e,query:t.query};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,o,i);return this.normalizeResponse(a)}catch(a){let l=a instanceof Error?a.message:String(a);throw this.logger(`Remote query failed for agent ${e}: ${l}`,"error"),a}}async execute(e,t){let n=this.requireConfig(e),o=n.tools?.execute??"crewx_executeAgent",i={agentId:n.agentId??e,task:t.task};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,o,i);return this.normalizeResponse(a)}catch(a){let l=a instanceof Error?a.message:String(a);throw this.logger(`Remote execute failed for agent ${e}: ${l}`,"error"),a}}mapToolNames(e,t){let n=this.requireConfig(e);n.tools={query:t.query??n.tools?.query??"crewx_queryAgent",execute:t.execute??n.tools?.execute??"crewx_executeAgent"},this.logger(`Updated tool name mapping for agent ${e}`,"debug");}async clearConfigs(){for(let e of this.transports.values())await e.close();this.configs.clear(),this.transports.clear(),this.logger("Cleared all remote agent configurations","debug");}requireConfig(e){let t=this.configs.get(e);if(!t)throw new Error(`Agent ${e} is not configured as a remote agent`);return t}async callRemoteTool(e,t,n){let o=this.transports.get(e);if(!o)throw new Error(`No transport available for agent ${e}`);let s={jsonrpc:"2.0",id:`${t}-${Date.now()}`,method:"tools/call",params:{name:t,arguments:n}};this.logger(`Calling remote MCP tool ${t} for agent ${e}`,"debug");let i=await o.send(s);if(i.error)throw new Error(i.error.message||"MCP server returned an error");return i.result}normalizeResponse(e){if(!e)return {success:false,content:[{type:"text",text:"Remote agent returned no response."}]};let t=e;if(Array.isArray(t.content)&&t.content.length>0)return t;let n=t.response??t.implementation??t.message??t.output,o=typeof n=="string"?n:JSON.stringify(n??e,null,2);return {...t,content:[{type:"text",text:o}]}}validateConfig(e){if(!e.url)throw new Error("Remote agent configuration requires a URL");if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("Remote agent URL must start with http:// or https://");if(e.type!=="mcp-http")throw new Error(`Unsupported remote agent type: ${e.type}`)}};});var ss={};zt(ss,{RemoteProviderRuntime:()=>exports.RemoteProviderRuntime,createRemoteProviderFactory:()=>os,resolveFileRemoteAgent:()=>Hc});function $c(r){let e=fs$1.readFileSync(r,"utf-8"),t=jsYaml.load(e);return {agents:Array.isArray(t?.agents)?t.agents:void 0}}function Dc(r){let e=Array.isArray(r.provider)?r.provider[0]:r.provider;return e||(Array.isArray(r.inline?.provider)?r.inline.provider[0]:r.inline?.provider)}function Hc(r,e=$c,t=fs$1.existsSync){let n=r.location.replace("file://","");if(!t(n))throw new Error(`Remote config file not found: ${n}`);if(!r.external_agent_id)throw new Error(`external_agent_id is required for file:// remote provider "${r.id}"`);let s=e(n).agents?.find(l=>l.id===r.external_agent_id);if(!s)throw new Error(`Agent "${r.external_agent_id}" not found in ${n}`);let i=Dc(s);if(!i)throw new Error(`Agent "${r.external_agent_id}" in ${n} has no provider configured`);if(i.startsWith("remote/"))throw new Error(`Chained remotes not allowed: ${r.id} \u2192 ${i}`);let a=X.resolve(X.dirname(n),s.working_directory??".");return {agent:{...s,working_directory:a},provider:i}}function os(r,e=pe){return (t,n)=>{let o=r.get(t);if(!o)throw new Error(`Remote provider "${t}" not found. Available: ${Array.from(r.keys()).join(", ")||"(none)"}`);if(o.location.startsWith("file://"))throw new Error(`Remote provider "${t}" uses file:// location which is not supported at the SDK level. Use the CLI commands (crewx query / crewx execute) which handle file:// remotes automatically.`);return new exports.RemoteProviderRuntime(t,o,e)}}function Lc(r,e){let t=e.location;if(!t)throw new Error("Remote provider config requires a location");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Unsupported remote location protocol for MCP-HTTP: ${t}`);return {type:"mcp-http",url:t,apiKey:e.apiKey,headers:e.headers,timeoutMs:e.timeout?.query??3e4,agentId:e.external_agent_id??r}}exports.RemoteProviderRuntime=void 0;var Tr=oe(()=>{y();Re();Cr();exports.RemoteProviderRuntime=class{manager;agentId;constructor(e,t,n=pe){this.agentId=t.external_agent_id??e,this.manager=new exports.RemoteAgentManager;let o=Lc(e,t);this.manager.loadConfig(this.agentId,o);}async query(e,t){return (await this.manager.query(this.agentId,{agentId:this.agentId,query:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(o=>o.text).join(`
32
+ ${t}:`]}}function Eo(r){return r?.tokens.map((e,t)=>({token:e,logprob:r.token_logprobs[t],topLogprobs:r.top_logprobs?Object.entries(r.top_logprobs[t]).map(([n,o])=>({token:n,logprob:o})):[]}))}var Bl=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode=void 0,this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}getArgs({mode:r,inputFormat:e,prompt:t,maxTokens:n,temperature:o,topP:s,topK:i,frequencyPenalty:a,presencePenalty:l,stopSequences:u,responseFormat:c,seed:m}){var p;let g=r.type,v=[];i!=null&&v.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:f,stopSequences:d}=Ul({prompt:t,inputFormat:e}),y=[...d??[],...u??[]],b={model:this.modelId,echo:this.settings.echo,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:n,temperature:o,top_p:s,frequency_penalty:a,presence_penalty:l,seed:m,prompt:f,stop:y.length>0?y:void 0};switch(g){case "regular":{if((p=r.tools)!=null&&p.length)throw new kt.UnsupportedFunctionalityError({functionality:"tools"});if(r.toolChoice)throw new kt.UnsupportedFunctionalityError({functionality:"toolChoice"});return {args:b,warnings:v}}case "object-json":throw new kt.UnsupportedFunctionalityError({functionality:"object-json mode"});case "object-tool":throw new kt.UnsupportedFunctionalityError({functionality:"object-tool mode"});default:{let k=g;throw new Error(`Unsupported type: ${k}`)}}}async doGenerate(r){let{args:e,warnings:t}=this.getArgs(r),{responseHeaders:n,value:o,rawValue:s}=await(0, ze.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0, ze.combineHeaders)(this.config.headers(),r.headers),body:e,failedResponseHandler:ue,successfulResponseHandler:(0, ze.createJsonResponseHandler)(Wl),abortSignal:r.abortSignal,fetch:this.config.fetch}),{prompt:i,...a}=e,l=o.choices[0];return {text:l.text,usage:{promptTokens:o.usage.prompt_tokens,completionTokens:o.usage.completion_tokens},finishReason:Pt(l.finish_reason),logprobs:Eo(l.logprobs),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:n,body:s},response:Et(o),warnings:t,request:{body:JSON.stringify(e)}}}async doStream(r){let{args:e,warnings:t}=this.getArgs(r),n={...e,stream:true,stream_options:this.config.compatibility==="strict"?{include_usage:true}:void 0},{responseHeaders:o,value:s}=await(0, ze.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0, ze.combineHeaders)(this.config.headers(),r.headers),body:n,failedResponseHandler:ue,successfulResponseHandler:(0, ze.createEventSourceResponseHandler)(Jl),abortSignal:r.abortSignal,fetch:this.config.fetch}),{prompt:i,...a}=e,l="unknown",u={promptTokens:Number.NaN,completionTokens:Number.NaN},c,m=true;return {stream:s.pipeThrough(new TransformStream({transform(p,g){if(!p.success){l="error",g.enqueue({type:"error",error:p.error});return}let v=p.value;if("error"in v){l="error",g.enqueue({type:"error",error:v.error});return}m&&(m=false,g.enqueue({type:"response-metadata",...Et(v)})),v.usage!=null&&(u={promptTokens:v.usage.prompt_tokens,completionTokens:v.usage.completion_tokens});let f=v.choices[0];f?.finish_reason!=null&&(l=Pt(f.finish_reason)),f?.text!=null&&g.enqueue({type:"text-delta",textDelta:f.text});let d=Eo(f?.logprobs);d?.length&&(c===void 0&&(c=[]),c.push(...d));},flush(p){p.enqueue({type:"finish",finishReason:l,logprobs:c,usage:u});}})),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:o},warnings:t,request:{body:JSON.stringify(n)}}}},Wl=N.z.object({id:N.z.string().nullish(),created:N.z.number().nullish(),model:N.z.string().nullish(),choices:N.z.array(N.z.object({text:N.z.string(),finish_reason:N.z.string(),logprobs:N.z.object({tokens:N.z.array(N.z.string()),token_logprobs:N.z.array(N.z.number()),top_logprobs:N.z.array(N.z.record(N.z.string(),N.z.number())).nullable()}).nullish()})),usage:N.z.object({prompt_tokens:N.z.number(),completion_tokens:N.z.number()})}),Jl=N.z.union([N.z.object({id:N.z.string().nullish(),created:N.z.number().nullish(),model:N.z.string().nullish(),choices:N.z.array(N.z.object({text:N.z.string(),finish_reason:N.z.string().nullish(),index:N.z.number(),logprobs:N.z.object({tokens:N.z.array(N.z.string()),token_logprobs:N.z.array(N.z.number()),top_logprobs:N.z.array(N.z.record(N.z.string(),N.z.number())).nullable()}).nullish()})),usage:N.z.object({prompt_tokens:N.z.number(),completion_tokens:N.z.number()}).nullish()}),wr]),Vl=q(),mr=G(),Ee=J("zod"),Gl=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var r;return (r=this.settings.maxEmbeddingsPerCall)!=null?r:2048}get supportsParallelCalls(){var r;return (r=this.settings.supportsParallelCalls)!=null?r:true}async doEmbed({values:r,headers:e,abortSignal:t}){if(r.length>this.maxEmbeddingsPerCall)throw new Vl.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:r});let{responseHeaders:n,value:o}=await(0, mr.postJsonToApi)({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:(0, mr.combineHeaders)(this.config.headers(),e),body:{model:this.modelId,input:r,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:ue,successfulResponseHandler:(0, mr.createJsonResponseHandler)(Kl),abortSignal:t,fetch:this.config.fetch});return {embeddings:o.data.map(s=>s.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,rawResponse:{headers:n}}}},Kl=Ee.z.object({data:Ee.z.array(Ee.z.object({embedding:Ee.z.array(Ee.z.number())})),usage:Ee.z.object({prompt_tokens:Ee.z.number()}).nullish()}),fr=G(),Ct=J("zod"),Xl={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Yl=new Set(["gpt-image-1"]),Ql=class{constructor(r,e,t){this.modelId=r,this.settings=e,this.config=t,this.specificationVersion="v1";}get maxImagesPerCall(){var r,e;return (e=(r=this.settings.maxImagesPerCall)!=null?r:Xl[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:r,n:e,size:t,aspectRatio:n,seed:o,providerOptions:s,headers:i,abortSignal:a}){var l,u,c,m;let p=[];n!=null&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&p.push({type:"unsupported-setting",setting:"seed"});let g=(c=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?c:new Date,{value:v,responseHeaders:f}=await(0, fr.postJsonToApi)({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:(0, fr.combineHeaders)(this.config.headers(),i),body:{model:this.modelId,prompt:r,n:e,size:t,...(m=s.openai)!=null?m:{},...Yl.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ue,successfulResponseHandler:(0, fr.createJsonResponseHandler)(Zl),abortSignal:a,fetch:this.config.fetch});return {images:v.data.map(d=>d.b64_json),warnings:p,response:{timestamp:g,modelId:this.modelId,headers:f}}}},Zl=Ct.z.object({data:Ct.z.array(Ct.z.object({b64_json:Ct.z.string()}))}),Ye=G(),K=J("zod"),eu=K.z.object({include:K.z.array(K.z.string()).nullish(),language:K.z.string().nullish(),prompt:K.z.string().nullish(),temperature:K.z.number().min(0).max(1).nullish().default(0),timestampGranularities:K.z.array(K.z.enum(["word","segment"])).nullish().default(["segment"])}),Ao={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},tu=class{constructor(r,e){this.modelId=r,this.config=e,this.specificationVersion="v1";}get provider(){return this.config.provider}getArgs({audio:r,mediaType:e,providerOptions:t}){var n,o,s,i,a;let l=[],u=(0, Ye.parseProviderOptions)({provider:"openai",providerOptions:t,schema:eu}),c=new FormData,m=r instanceof Uint8Array?new Blob([r]):new Blob([(0, Ye.convertBase64ToUint8Array)(r)]);if(c.append("model",this.modelId),c.append("file",new File([m],"audio",{type:e})),u){let p={include:(n=u.include)!=null?n:void 0,language:(o=u.language)!=null?o:void 0,prompt:(s=u.prompt)!=null?s:void 0,temperature:(i=u.temperature)!=null?i:void 0,timestamp_granularities:(a=u.timestampGranularities)!=null?a:void 0};for(let g in p){let v=p[g];v!==void 0&&c.append(g,String(v));}}return {formData:c,warnings:l}}async doGenerate(r){var e,t,n,o,s,i;let a=(n=(t=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:t.call(e))!=null?n:new Date,{formData:l,warnings:u}=this.getArgs(r),{value:c,responseHeaders:m,rawValue:p}=await(0, Ye.postFormDataToApi)({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:(0, Ye.combineHeaders)(this.config.headers(),r.headers),formData:l,failedResponseHandler:ue,successfulResponseHandler:(0, Ye.createJsonResponseHandler)(ru),abortSignal:r.abortSignal,fetch:this.config.fetch}),g=c.language!=null&&c.language in Ao?Ao[c.language]:void 0;return {text:c.text,segments:(s=(o=c.words)==null?void 0:o.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?s:[],language:g,durationInSeconds:(i=c.duration)!=null?i:void 0,warnings:u,response:{timestamp:a,modelId:this.modelId,headers:m,body:p}}}},ru=K.z.object({text:K.z.string(),language:K.z.string().nullish(),duration:K.z.number().nullish(),words:K.z.array(K.z.object({word:K.z.string(),start:K.z.number(),end:K.z.number()})).nullish()}),nu=q(),he=G(),_=J("zod"),So=q(),ou=G();function su({prompt:r,systemMessageMode:e}){let t=[],n=[];for(let{role:o,content:s}of r)switch(o){case "system":{switch(e){case "system":{t.push({role:"system",content:s});break}case "developer":{t.push({role:"developer",content:s});break}case "remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{let i=e;throw new Error(`Unsupported system message mode: ${i}`)}}break}case "user":{t.push({role:"user",content:s.map((i,a)=>{var l,u,c,m;switch(i.type){case "text":return {type:"input_text",text:i.text};case "image":return {type:"input_image",image_url:i.image instanceof URL?i.image.toString():`data:${(l=i.mimeType)!=null?l:"image/jpeg"};base64,${(0, ou.convertUint8ArrayToBase64)(i.image)}`,detail:(c=(u=i.providerMetadata)==null?void 0:u.openai)==null?void 0:c.imageDetail};case "file":{if(i.data instanceof URL)throw new So.UnsupportedFunctionalityError({functionality:"File URLs in user messages"});if(i.mimeType==="application/pdf")return {type:"input_file",filename:(m=i.filename)!=null?m:`part-${a}.pdf`,file_data:`data:application/pdf;base64,${i.data}`};throw new So.UnsupportedFunctionalityError({functionality:"Only PDF files are supported in user messages"})}}})});break}case "assistant":{for(let i of s)switch(i.type){case "text":{t.push({role:"assistant",content:[{type:"output_text",text:i.text}]});break}case "tool-call":{t.push({type:"function_call",call_id:i.toolCallId,name:i.toolName,arguments:JSON.stringify(i.args)});break}}break}case "tool":{for(let i of s)t.push({type:"function_call_output",call_id:i.toolCallId,output:JSON.stringify(i.result)});break}default:{let i=o;throw new Error(`Unsupported role: ${i}`)}}return {messages:t,warnings:n}}function Io({finishReason:r,hasToolCalls:e}){switch(r){case void 0:case null:return e?"tool-calls":"stop";case "max_output_tokens":return "length";case "content_filter":return "content-filter";default:return e?"tool-calls":"unknown"}}var iu=q();function au({mode:r,strict:e}){var t;let n=(t=r.tools)!=null&&t.length?r.tools:void 0,o=[];if(n==null)return {tools:void 0,tool_choice:void 0,toolWarnings:o};let s=r.toolChoice,i=[];for(let l of n)switch(l.type){case "function":i.push({type:"function",name:l.name,description:l.description,parameters:l.parameters,strict:e?true:void 0});break;case "provider-defined":l.id==="openai.web_search_preview"?i.push({type:"web_search_preview",search_context_size:l.args.searchContextSize,user_location:l.args.userLocation}):o.push({type:"unsupported-tool",tool:l});break;default:o.push({type:"unsupported-tool",tool:l});break}if(s==null)return {tools:i,tool_choice:void 0,toolWarnings:o};let a=s.type;switch(a){case "auto":case "none":case "required":return {tools:i,tool_choice:a,toolWarnings:o};case "tool":return s.toolName==="web_search_preview"?{tools:i,tool_choice:{type:"web_search_preview"},toolWarnings:o}:{tools:i,tool_choice:{type:"function",name:s.toolName},toolWarnings:o};default:{let l=a;throw new iu.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${l}`})}}}var lu=class{constructor(r,e){this.specificationVersion="v1",this.defaultObjectGenerationMode="json",this.supportsStructuredOutputs=true,this.modelId=r,this.config=e;}get provider(){return this.config.provider}getArgs({mode:r,maxTokens:e,temperature:t,stopSequences:n,topP:o,topK:s,presencePenalty:i,frequencyPenalty:a,seed:l,prompt:u,providerMetadata:c,responseFormat:m}){var p,g,v;let f=[],d=Eu(this.modelId),y=r.type;s!=null&&f.push({type:"unsupported-setting",setting:"topK"}),l!=null&&f.push({type:"unsupported-setting",setting:"seed"}),i!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&f.push({type:"unsupported-setting",setting:"stopSequences"});let{messages:b,warnings:k}=su({prompt:u,systemMessageMode:d.systemMessageMode});f.push(...k);let w=(0, he.parseProviderOptions)({provider:"openai",providerOptions:c,schema:Au}),x=(p=w?.strictSchemas)!=null?p:true,S={model:this.modelId,input:b,temperature:t,top_p:o,max_output_tokens:e,...m?.type==="json"&&{text:{format:m.schema!=null?{type:"json_schema",strict:x,name:(g=m.name)!=null?g:"response",description:m.description,schema:m.schema}:{type:"json_object"}}},metadata:w?.metadata,parallel_tool_calls:w?.parallelToolCalls,previous_response_id:w?.previousResponseId,store:w?.store,user:w?.user,instructions:w?.instructions,...d.isReasoningModel&&(w?.reasoningEffort!=null||w?.reasoningSummary!=null)&&{reasoning:{...w?.reasoningEffort!=null&&{effort:w.reasoningEffort},...w?.reasoningSummary!=null&&{summary:w.reasoningSummary}}},...d.requiredAutoTruncation};switch(d.isReasoningModel&&(S.temperature!=null&&(S.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))),y){case "regular":{let{tools:z,tool_choice:R,toolWarnings:T}=au({mode:r,strict:x});return {args:{...S,tools:z,tool_choice:R},warnings:[...f,...T]}}case "object-json":return {args:{...S,text:{format:r.schema!=null?{type:"json_schema",strict:x,name:(v=r.name)!=null?v:"response",description:r.description,schema:r.schema}:{type:"json_object"}}},warnings:f};case "object-tool":return {args:{...S,tool_choice:{type:"function",name:r.tool.name},tools:[{type:"function",name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters,strict:x}]},warnings:f};default:{let z=y;throw new Error(`Unsupported type: ${z}`)}}}async doGenerate(r){var e,t,n,o,s,i,a;let{args:l,warnings:u}=this.getArgs(r),c=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:m,value:p,rawValue:g}=await(0, he.postJsonToApi)({url:c,headers:(0, he.combineHeaders)(this.config.headers(),r.headers),body:l,failedResponseHandler:ue,successfulResponseHandler:(0, he.createJsonResponseHandler)(_.z.object({id:_.z.string(),created_at:_.z.number(),error:_.z.object({message:_.z.string(),code:_.z.string()}).nullish(),model:_.z.string(),output:_.z.array(_.z.discriminatedUnion("type",[_.z.object({type:_.z.literal("message"),role:_.z.literal("assistant"),content:_.z.array(_.z.object({type:_.z.literal("output_text"),text:_.z.string(),annotations:_.z.array(_.z.object({type:_.z.literal("url_citation"),start_index:_.z.number(),end_index:_.z.number(),url:_.z.string(),title:_.z.string()}))}))}),_.z.object({type:_.z.literal("function_call"),call_id:_.z.string(),name:_.z.string(),arguments:_.z.string()}),_.z.object({type:_.z.literal("web_search_call")}),_.z.object({type:_.z.literal("computer_call")}),_.z.object({type:_.z.literal("reasoning"),summary:_.z.array(_.z.object({type:_.z.literal("summary_text"),text:_.z.string()}))})])),incomplete_details:_.z.object({reason:_.z.string()}).nullable(),usage:Mo})),abortSignal:r.abortSignal,fetch:this.config.fetch});if(p.error)throw new nu.APICallError({message:p.error.message,url:c,requestBodyValues:l,statusCode:400,responseHeaders:m,responseBody:g,isRetryable:false});let v=p.output.filter(y=>y.type==="message").flatMap(y=>y.content).filter(y=>y.type==="output_text"),f=p.output.filter(y=>y.type==="function_call").map(y=>({toolCallType:"function",toolCallId:y.call_id,toolName:y.name,args:y.arguments})),d=(t=(e=p.output.find(y=>y.type==="reasoning"))==null?void 0:e.summary)!=null?t:null;return {text:v.map(y=>y.text).join(`
33
+ `),sources:v.flatMap(y=>y.annotations.map(b=>{var k,w,x;return {sourceType:"url",id:(x=(w=(k=this.config).generateId)==null?void 0:w.call(k))!=null?x:(0, he.generateId)(),url:b.url,title:b.title}})),finishReason:Io({finishReason:(n=p.incomplete_details)==null?void 0:n.reason,hasToolCalls:f.length>0}),toolCalls:f.length>0?f:void 0,reasoning:d?d.map(y=>({type:"text",text:y.text})):void 0,usage:{promptTokens:p.usage.input_tokens,completionTokens:p.usage.output_tokens},rawCall:{rawPrompt:void 0,rawSettings:{}},rawResponse:{headers:m,body:g},request:{body:JSON.stringify(l)},response:{id:p.id,timestamp:new Date(p.created_at*1e3),modelId:p.model},providerMetadata:{openai:{responseId:p.id,cachedPromptTokens:(s=(o=p.usage.input_tokens_details)==null?void 0:o.cached_tokens)!=null?s:null,reasoningTokens:(a=(i=p.usage.output_tokens_details)==null?void 0:i.reasoning_tokens)!=null?a:null}},warnings:u}}async doStream(r){let{args:e,warnings:t}=this.getArgs(r),{responseHeaders:n,value:o}=await(0, he.postJsonToApi)({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:(0, he.combineHeaders)(this.config.headers(),r.headers),body:{...e,stream:true},failedResponseHandler:ue,successfulResponseHandler:(0, he.createEventSourceResponseHandler)(vu),abortSignal:r.abortSignal,fetch:this.config.fetch}),s=this,i="unknown",a=NaN,l=NaN,u=null,c=null,m=null,p={},g=false;return {stream:o.pipeThrough(new TransformStream({transform(v,f){var d,y,b,k,w,x,S,z;if(!v.success){i="error",f.enqueue({type:"error",error:v.error});return}let R=v.value;if(Ru(R))R.item.type==="function_call"&&(p[R.output_index]={toolName:R.item.name,toolCallId:R.item.call_id},f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:R.item.call_id,toolName:R.item.name,argsTextDelta:R.item.arguments}));else if(ku(R)){let T=p[R.output_index];T!=null&&f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:T.toolCallId,toolName:T.toolName,argsTextDelta:R.delta});}else xu(R)?(m=R.response.id,f.enqueue({type:"response-metadata",id:R.response.id,timestamp:new Date(R.response.created_at*1e3),modelId:R.response.model})):wu(R)?f.enqueue({type:"text-delta",textDelta:R.delta}):Tu(R)?f.enqueue({type:"reasoning",textDelta:R.delta}):bu(R)&&R.item.type==="function_call"?(p[R.output_index]=void 0,g=true,f.enqueue({type:"tool-call",toolCallType:"function",toolCallId:R.item.call_id,toolName:R.item.name,args:R.item.arguments})):_u(R)?(i=Io({finishReason:(d=R.response.incomplete_details)==null?void 0:d.reason,hasToolCalls:g}),a=R.response.usage.input_tokens,l=R.response.usage.output_tokens,u=(b=(y=R.response.usage.input_tokens_details)==null?void 0:y.cached_tokens)!=null?b:u,c=(w=(k=R.response.usage.output_tokens_details)==null?void 0:k.reasoning_tokens)!=null?w:c):Cu(R)?f.enqueue({type:"source",source:{sourceType:"url",id:(z=(S=(x=s.config).generateId)==null?void 0:S.call(x))!=null?z:(0, he.generateId)(),url:R.annotation.url,title:R.annotation.title}}):Pu(R)&&f.enqueue({type:"error",error:R});},flush(v){v.enqueue({type:"finish",finishReason:i,usage:{promptTokens:a,completionTokens:l},...(u!=null||c!=null)&&{providerMetadata:{openai:{responseId:m,cachedPromptTokens:u,reasoningTokens:c}}}});}})),rawCall:{rawPrompt:void 0,rawSettings:{}},rawResponse:{headers:n},request:{body:JSON.stringify(e)},warnings:t}}},Mo=_.z.object({input_tokens:_.z.number(),input_tokens_details:_.z.object({cached_tokens:_.z.number().nullish()}).nullish(),output_tokens:_.z.number(),output_tokens_details:_.z.object({reasoning_tokens:_.z.number().nullish()}).nullish()}),uu=_.z.object({type:_.z.literal("response.output_text.delta"),delta:_.z.string()}),cu=_.z.object({type:_.z.enum(["response.completed","response.incomplete"]),response:_.z.object({incomplete_details:_.z.object({reason:_.z.string()}).nullish(),usage:Mo})}),du=_.z.object({type:_.z.literal("response.created"),response:_.z.object({id:_.z.string(),created_at:_.z.number(),model:_.z.string()})}),pu=_.z.object({type:_.z.literal("response.output_item.done"),output_index:_.z.number(),item:_.z.discriminatedUnion("type",[_.z.object({type:_.z.literal("message")}),_.z.object({type:_.z.literal("function_call"),id:_.z.string(),call_id:_.z.string(),name:_.z.string(),arguments:_.z.string(),status:_.z.literal("completed")})])}),gu=_.z.object({type:_.z.literal("response.function_call_arguments.delta"),item_id:_.z.string(),output_index:_.z.number(),delta:_.z.string()}),mu=_.z.object({type:_.z.literal("response.output_item.added"),output_index:_.z.number(),item:_.z.discriminatedUnion("type",[_.z.object({type:_.z.literal("message")}),_.z.object({type:_.z.literal("function_call"),id:_.z.string(),call_id:_.z.string(),name:_.z.string(),arguments:_.z.string()})])}),fu=_.z.object({type:_.z.literal("response.output_text.annotation.added"),annotation:_.z.object({type:_.z.literal("url_citation"),url:_.z.string(),title:_.z.string()})}),hu=_.z.object({type:_.z.literal("response.reasoning_summary_text.delta"),item_id:_.z.string(),output_index:_.z.number(),summary_index:_.z.number(),delta:_.z.string()}),yu=_.z.object({type:_.z.literal("error"),code:_.z.string(),message:_.z.string(),param:_.z.string().nullish(),sequence_number:_.z.number()}),vu=_.z.union([uu,cu,du,pu,gu,mu,fu,hu,yu,_.z.object({type:_.z.string()}).passthrough()]);function wu(r){return r.type==="response.output_text.delta"}function bu(r){return r.type==="response.output_item.done"}function _u(r){return r.type==="response.completed"||r.type==="response.incomplete"}function xu(r){return r.type==="response.created"}function ku(r){return r.type==="response.function_call_arguments.delta"}function Ru(r){return r.type==="response.output_item.added"}function Cu(r){return r.type==="response.output_text.annotation.added"}function Tu(r){return r.type==="response.reasoning_summary_text.delta"}function Pu(r){return r.type==="error"}function Eu(r){return r.startsWith("o")||r.startsWith("gpt-5")?r.startsWith("o1-mini")||r.startsWith("o1-preview")?{isReasoningModel:true,systemMessageMode:"remove",requiredAutoTruncation:false}:{isReasoningModel:true,systemMessageMode:"developer",requiredAutoTruncation:false}:{isReasoningModel:false,systemMessageMode:"system",requiredAutoTruncation:false}}var Au=_.z.object({metadata:_.z.any().nullish(),parallelToolCalls:_.z.boolean().nullish(),previousResponseId:_.z.string().nullish(),store:_.z.boolean().nullish(),user:_.z.string().nullish(),reasoningEffort:_.z.string().nullish(),strictSchemas:_.z.boolean().nullish(),instructions:_.z.string().nullish(),reasoningSummary:_.z.string().nullish()}),Su=J("zod"),Iu=Su.z.object({});function Ou({searchContextSize:r,userLocation:e}={}){return {type:"provider-defined",id:"openai.web_search_preview",args:{searchContextSize:r,userLocation:e},parameters:Iu}}var zu={webSearchPreview:Ou},Tt=G(),hr=J("zod"),Mu=hr.z.object({instructions:hr.z.string().nullish(),speed:hr.z.number().min(.25).max(4).default(1).nullish()}),ju=class{constructor(r,e){this.modelId=r,this.config=e,this.specificationVersion="v1";}get provider(){return this.config.provider}getArgs({text:r,voice:e="alloy",outputFormat:t="mp3",speed:n,instructions:o,providerOptions:s}){let i=[],a=(0, Tt.parseProviderOptions)({provider:"openai",providerOptions:s,schema:Mu}),l={model:this.modelId,input:r,voice:e,response_format:"mp3",speed:n,instructions:o};if(t&&(["mp3","opus","aac","flac","wav","pcm"].includes(t)?l.response_format=t:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${t}. Using mp3 instead.`})),a){let u={};for(let c in u){let m=u[c];m!==void 0&&(l[c]=m);}}return {requestBody:l,warnings:i}}async doGenerate(r){var e,t,n;let o=(n=(t=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:t.call(e))!=null?n:new Date,{requestBody:s,warnings:i}=this.getArgs(r),{value:a,responseHeaders:l,rawValue:u}=await(0, Tt.postJsonToApi)({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:(0, Tt.combineHeaders)(this.config.headers(),r.headers),body:s,failedResponseHandler:ue,successfulResponseHandler:(0, Tt.createBinaryResponseHandler)(),abortSignal:r.abortSignal,fetch:this.config.fetch});return {audio:a,warnings:i,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}};function jo(r={}){var e,t,n;let o=(e=(0, Co.withoutTrailingSlash)(r.baseURL))!=null?e:"https://api.openai.com/v1",s=(t=r.compatibility)!=null?t:"compatible",i=(n=r.name)!=null?n:"openai",a=()=>({Authorization:`Bearer ${(0, Co.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":r.organization,"OpenAI-Project":r.project,...r.headers}),l=(y,b={})=>new Dl(y,b,{provider:`${i}.chat`,url:({path:k})=>`${o}${k}`,headers:a,compatibility:s,fetch:r.fetch}),u=(y,b={})=>new Bl(y,b,{provider:`${i}.completion`,url:({path:k})=>`${o}${k}`,headers:a,compatibility:s,fetch:r.fetch}),c=(y,b={})=>new Gl(y,b,{provider:`${i}.embedding`,url:({path:k})=>`${o}${k}`,headers:a,fetch:r.fetch}),m=(y,b={})=>new Ql(y,b,{provider:`${i}.image`,url:({path:k})=>`${o}${k}`,headers:a,fetch:r.fetch}),p=y=>new tu(y,{provider:`${i}.transcription`,url:({path:b})=>`${o}${b}`,headers:a,fetch:r.fetch}),g=y=>new ju(y,{provider:`${i}.speech`,url:({path:b})=>`${o}${b}`,headers:a,fetch:r.fetch}),v=(y,b)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return y==="gpt-3.5-turbo-instruct"?u(y,b):l(y,b)},f=y=>new lu(y,{provider:`${i}.responses`,url:({path:b})=>`${o}${b}`,headers:a,fetch:r.fetch}),d=function(y,b){return v(y,b)};return d.languageModel=v,d.chat=l,d.completion=u,d.responses=f,d.embedding=c,d.textEmbedding=c,d.textEmbeddingModel=c,d.image=m,d.imageModel=m,d.transcription=p,d.transcriptionModel=p,d.speech=g,d.speechModel=g,d.tools=zu,d}var Nu=jo({compatibility:"strict"});});var Wo=_e((nf,Bo)=>{h();var _r=Object.defineProperty,Du=Object.getOwnPropertyDescriptor,$u=Object.getOwnPropertyNames,Hu=Object.prototype.hasOwnProperty,Lu=(r,e)=>{for(var t in e)_r(r,t,{get:e[t],enumerable:true});},qu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $u(e))!Hu.call(r,o)&&o!==t&&_r(r,o,{get:()=>e[o],enumerable:!(n=Du(e,o))||n.enumerable});return r},Fu=r=>qu(_r({},"__esModule",{value:true}),r),Fo={};Lu(Fo,{anthropic:()=>mc,createAnthropic:()=>Uo});Bo.exports=Fu(Fo);var Uu=q(),Do=G(),$o=q(),Ae=G(),C=J("zod"),Bu=G(),Qe=J("zod"),Wu=Qe.z.object({type:Qe.z.literal("error"),error:Qe.z.object({type:Qe.z.string(),message:Qe.z.string()})}),Ho=(0, Bu.createJsonErrorResponseHandler)({errorSchema:Wu,errorToMessage:r=>r.error.message}),Ju=q();function Vu(r){var e;let t=(e=r.tools)!=null&&e.length?r.tools:void 0,n=[],o=new Set;if(t==null)return {tools:void 0,tool_choice:void 0,toolWarnings:n,betas:o};let s=[];for(let l of t)switch(l.type){case "function":s.push({name:l.name,description:l.description,input_schema:l.parameters});break;case "provider-defined":switch(l.id){case "anthropic.computer_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"computer_20250124",display_width_px:l.args.displayWidthPx,display_height_px:l.args.displayHeightPx,display_number:l.args.displayNumber});break;case "anthropic.computer_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"computer_20241022",display_width_px:l.args.displayWidthPx,display_height_px:l.args.displayHeightPx,display_number:l.args.displayNumber});break;case "anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"text_editor_20250124"});break;case "anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"text_editor_20241022"});break;case "anthropic.bash_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"bash_20250124"});break;case "anthropic.bash_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"bash_20241022"});break;default:n.push({type:"unsupported-tool",tool:l});break}break;default:n.push({type:"unsupported-tool",tool:l});break}let i=r.toolChoice;if(i==null)return {tools:s,tool_choice:void 0,toolWarnings:n,betas:o};let a=i.type;switch(a){case "auto":return {tools:s,tool_choice:{type:"auto"},toolWarnings:n,betas:o};case "required":return {tools:s,tool_choice:{type:"any"},toolWarnings:n,betas:o};case "none":return {tools:void 0,tool_choice:void 0,toolWarnings:n,betas:o};case "tool":return {tools:s,tool_choice:{type:"tool",name:i.toolName},toolWarnings:n,betas:o};default:{let l=a;throw new Ju.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${l}`})}}}var Lo=q(),Gu=G();function Ku({prompt:r,sendReasoning:e,warnings:t}){var n,o,s,i;let a=new Set,l=Xu(r),u,c=[];function m(p){var g;let v=p?.anthropic;return (g=v?.cacheControl)!=null?g:v?.cache_control}for(let p=0;p<l.length;p++){let g=l[p],v=p===l.length-1,f=g.type;switch(f){case "system":{if(u!=null)throw new Lo.UnsupportedFunctionalityError({functionality:"Multiple system messages that are separated by user/assistant messages"});u=g.messages.map(({content:d,providerMetadata:y})=>({type:"text",text:d,cache_control:m(y)}));break}case "user":{let d=[];for(let y of g.messages){let{role:b,content:k}=y;switch(b){case "user":{for(let w=0;w<k.length;w++){let x=k[w],S=w===k.length-1,z=(n=m(x.providerMetadata))!=null?n:S?m(y.providerMetadata):void 0;switch(x.type){case "text":{d.push({type:"text",text:x.text,cache_control:z});break}case "image":{d.push({type:"image",source:x.image instanceof URL?{type:"url",url:x.image.toString()}:{type:"base64",media_type:(o=x.mimeType)!=null?o:"image/jpeg",data:(0, Gu.convertUint8ArrayToBase64)(x.image)},cache_control:z});break}case "file":{if(x.mimeType!=="application/pdf")throw new Lo.UnsupportedFunctionalityError({functionality:"Non-PDF files in user messages"});a.add("pdfs-2024-09-25"),d.push({type:"document",source:x.data instanceof URL?{type:"url",url:x.data.toString()}:{type:"base64",media_type:"application/pdf",data:x.data},cache_control:z});break}}}break}case "tool":{for(let w=0;w<k.length;w++){let x=k[w],S=w===k.length-1,z=(s=m(x.providerMetadata))!=null?s:S?m(y.providerMetadata):void 0,R=x.content!=null?x.content.map(T=>{var O;switch(T.type){case "text":return {type:"text",text:T.text,cache_control:void 0};case "image":return {type:"image",source:{type:"base64",media_type:(O=T.mimeType)!=null?O:"image/jpeg",data:T.data},cache_control:void 0}}}):JSON.stringify(x.result);d.push({type:"tool_result",tool_use_id:x.toolCallId,content:R,is_error:x.isError,cache_control:z});}break}default:{let w=b;throw new Error(`Unsupported role: ${w}`)}}}c.push({role:"user",content:d});break}case "assistant":{let d=[];for(let y=0;y<g.messages.length;y++){let b=g.messages[y],k=y===g.messages.length-1,{content:w}=b;for(let x=0;x<w.length;x++){let S=w[x],z=x===w.length-1,R=(i=m(S.providerMetadata))!=null?i:z?m(b.providerMetadata):void 0;switch(S.type){case "text":{d.push({type:"text",text:v&&k&&z?S.text.trim():S.text,cache_control:R});break}case "reasoning":{e?d.push({type:"thinking",thinking:S.text,signature:S.signature,cache_control:R}):t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case "redacted-reasoning":{d.push({type:"redacted_thinking",data:S.data,cache_control:R});break}case "tool-call":{d.push({type:"tool_use",id:S.toolCallId,name:S.toolName,input:S.args,cache_control:R});break}}}}c.push({role:"assistant",content:d});break}default:{let d=f;throw new Error(`Unsupported type: ${d}`)}}}return {prompt:{system:u,messages:c},betas:a}}function Xu(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case "system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case "assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case "user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case "tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let s=o;throw new Error(`Unsupported role: ${s}`)}}}return e}function qo(r){switch(r){case "end_turn":case "stop_sequence":return "stop";case "tool_use":return "tool-calls";case "max_tokens":return "length";default:return "unknown"}}var Yu=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode="tool",this.modelId=r,this.settings=e,this.config=t;}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get supportsImageUrls(){return this.config.supportsImageUrls}async getArgs({mode:r,prompt:e,maxTokens:t=4096,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:c,providerMetadata:m}){var p,g,v;let f=r.type,d=[];i!=null&&d.push({type:"unsupported-setting",setting:"frequencyPenalty"}),a!=null&&d.push({type:"unsupported-setting",setting:"presencePenalty"}),c!=null&&d.push({type:"unsupported-setting",setting:"seed"}),u!=null&&u.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:y,betas:b}=Ku({prompt:e,sendReasoning:(p=this.settings.sendReasoning)!=null?p:true,warnings:d}),k=(0, Ae.parseProviderOptions)({provider:"anthropic",providerOptions:m,schema:ec}),w=((g=k?.thinking)==null?void 0:g.type)==="enabled",x=(v=k?.thinking)==null?void 0:v.budgetTokens,S={model:this.modelId,max_tokens:t,temperature:n,top_k:s,top_p:o,stop_sequences:l,...w&&{thinking:{type:"enabled",budget_tokens:x}},system:y.system,messages:y.messages};if(w){if(x==null)throw new $o.UnsupportedFunctionalityError({functionality:"thinking requires a budget"});S.temperature!=null&&(S.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),s!=null&&(S.top_k=void 0,d.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(S.top_p=void 0,d.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),S.max_tokens=t+x;}switch(f){case "regular":{let{tools:z,tool_choice:R,toolWarnings:T,betas:O}=Vu(r);return {args:{...S,tools:z,tool_choice:R},warnings:[...d,...T],betas:new Set([...b,...O])}}case "object-json":throw new $o.UnsupportedFunctionalityError({functionality:"json-mode object generation"});case "object-tool":{let{name:z,description:R,parameters:T}=r.tool;return {args:{...S,tools:[{name:z,description:R,input_schema:T}],tool_choice:{type:"tool",name:z}},warnings:d,betas:b}}default:{let z=f;throw new Error(`Unsupported type: ${z}`)}}}async getHeaders({betas:r,headers:e}){return (0, Ae.combineHeaders)(await(0, Ae.resolve)(this.config.headers),r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{},e)}buildRequestUrl(r){var e,t,n;return (n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r){var e,t,n;return (n=(t=(e=this.config).transformRequestBody)==null?void 0:t.call(e,r))!=null?n:r}async doGenerate(r){var e,t,n,o;let{args:s,warnings:i,betas:a}=await this.getArgs(r),{responseHeaders:l,value:u,rawValue:c}=await(0, Ae.postJsonToApi)({url:this.buildRequestUrl(false),headers:await this.getHeaders({betas:a,headers:r.headers}),body:this.transformRequestBody(s),failedResponseHandler:Ho,successfulResponseHandler:(0, Ae.createJsonResponseHandler)(Qu),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:m,...p}=s,g="";for(let d of u.content)d.type==="text"&&(g+=d.text);let v;if(u.content.some(d=>d.type==="tool_use")){v=[];for(let d of u.content)d.type==="tool_use"&&v.push({toolCallType:"function",toolCallId:d.id,toolName:d.name,args:JSON.stringify(d.input)});}let f=u.content.filter(d=>d.type==="redacted_thinking"||d.type==="thinking").map(d=>d.type==="thinking"?{type:"text",text:d.thinking,signature:d.signature}:{type:"redacted",data:d.data});return {text:g,reasoning:f.length>0?f:void 0,toolCalls:v,finishReason:qo(u.stop_reason),usage:{promptTokens:u.usage.input_tokens,completionTokens:u.usage.output_tokens},rawCall:{rawPrompt:m,rawSettings:p},rawResponse:{headers:l,body:c},response:{id:(e=u.id)!=null?e:void 0,modelId:(t=u.model)!=null?t:void 0},warnings:i,providerMetadata:{anthropic:{cacheCreationInputTokens:(n=u.usage.cache_creation_input_tokens)!=null?n:null,cacheReadInputTokens:(o=u.usage.cache_read_input_tokens)!=null?o:null}},request:{body:JSON.stringify(s)}}}async doStream(r){let{args:e,warnings:t,betas:n}=await this.getArgs(r),o={...e,stream:true},{responseHeaders:s,value:i}=await(0, Ae.postJsonToApi)({url:this.buildRequestUrl(true),headers:await this.getHeaders({betas:n,headers:r.headers}),body:this.transformRequestBody(o),failedResponseHandler:Ho,successfulResponseHandler:(0, Ae.createEventSourceResponseHandler)(Zu),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:a,...l}=e,u="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},m={},p,g;return {stream:i.pipeThrough(new TransformStream({transform(v,f){var d,y,b,k;if(!v.success){f.enqueue({type:"error",error:v.error});return}let w=v.value;switch(w.type){case "ping":return;case "content_block_start":{let x=w.content_block.type;switch(g=x,x){case "text":case "thinking":return;case "redacted_thinking":{f.enqueue({type:"redacted-reasoning",data:w.content_block.data});return}case "tool_use":{m[w.index]={toolCallId:w.content_block.id,toolName:w.content_block.name,jsonText:""};return}default:{let S=x;throw new Error(`Unsupported content block type: ${S}`)}}}case "content_block_stop":{if(m[w.index]!=null){let x=m[w.index];f.enqueue({type:"tool-call",toolCallType:"function",toolCallId:x.toolCallId,toolName:x.toolName,args:x.jsonText}),delete m[w.index];}g=void 0;return}case "content_block_delta":{let x=w.delta.type;switch(x){case "text_delta":{f.enqueue({type:"text-delta",textDelta:w.delta.text});return}case "thinking_delta":{f.enqueue({type:"reasoning",textDelta:w.delta.thinking});return}case "signature_delta":{g==="thinking"&&f.enqueue({type:"reasoning-signature",signature:w.delta.signature});return}case "input_json_delta":{let S=m[w.index];f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:S.toolCallId,toolName:S.toolName,argsTextDelta:w.delta.partial_json}),S.jsonText+=w.delta.partial_json;return}default:{let S=x;throw new Error(`Unsupported delta type: ${S}`)}}}case "message_start":{c.promptTokens=w.message.usage.input_tokens,c.completionTokens=w.message.usage.output_tokens,p={anthropic:{cacheCreationInputTokens:(d=w.message.usage.cache_creation_input_tokens)!=null?d:null,cacheReadInputTokens:(y=w.message.usage.cache_read_input_tokens)!=null?y:null}},f.enqueue({type:"response-metadata",id:(b=w.message.id)!=null?b:void 0,modelId:(k=w.message.model)!=null?k:void 0});return}case "message_delta":{c.completionTokens=w.usage.output_tokens,u=qo(w.delta.stop_reason);return}case "message_stop":{f.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:p});return}case "error":{f.enqueue({type:"error",error:w.error});return}default:{let x=w;throw new Error(`Unsupported chunk type: ${x}`)}}}})),rawCall:{rawPrompt:a,rawSettings:l},rawResponse:{headers:s},warnings:t,request:{body:JSON.stringify(o)}}}},Qu=C.z.object({type:C.z.literal("message"),id:C.z.string().nullish(),model:C.z.string().nullish(),content:C.z.array(C.z.discriminatedUnion("type",[C.z.object({type:C.z.literal("text"),text:C.z.string()}),C.z.object({type:C.z.literal("thinking"),thinking:C.z.string(),signature:C.z.string()}),C.z.object({type:C.z.literal("redacted_thinking"),data:C.z.string()}),C.z.object({type:C.z.literal("tool_use"),id:C.z.string(),name:C.z.string(),input:C.z.unknown()})])),stop_reason:C.z.string().nullish(),usage:C.z.object({input_tokens:C.z.number(),output_tokens:C.z.number(),cache_creation_input_tokens:C.z.number().nullish(),cache_read_input_tokens:C.z.number().nullish()})}),Zu=C.z.discriminatedUnion("type",[C.z.object({type:C.z.literal("message_start"),message:C.z.object({id:C.z.string().nullish(),model:C.z.string().nullish(),usage:C.z.object({input_tokens:C.z.number(),output_tokens:C.z.number(),cache_creation_input_tokens:C.z.number().nullish(),cache_read_input_tokens:C.z.number().nullish()})})}),C.z.object({type:C.z.literal("content_block_start"),index:C.z.number(),content_block:C.z.discriminatedUnion("type",[C.z.object({type:C.z.literal("text"),text:C.z.string()}),C.z.object({type:C.z.literal("thinking"),thinking:C.z.string()}),C.z.object({type:C.z.literal("tool_use"),id:C.z.string(),name:C.z.string()}),C.z.object({type:C.z.literal("redacted_thinking"),data:C.z.string()})])}),C.z.object({type:C.z.literal("content_block_delta"),index:C.z.number(),delta:C.z.discriminatedUnion("type",[C.z.object({type:C.z.literal("input_json_delta"),partial_json:C.z.string()}),C.z.object({type:C.z.literal("text_delta"),text:C.z.string()}),C.z.object({type:C.z.literal("thinking_delta"),thinking:C.z.string()}),C.z.object({type:C.z.literal("signature_delta"),signature:C.z.string()})])}),C.z.object({type:C.z.literal("content_block_stop"),index:C.z.number()}),C.z.object({type:C.z.literal("error"),error:C.z.object({type:C.z.string(),message:C.z.string()})}),C.z.object({type:C.z.literal("message_delta"),delta:C.z.object({stop_reason:C.z.string().nullish()}),usage:C.z.object({output_tokens:C.z.number()})}),C.z.object({type:C.z.literal("message_stop")}),C.z.object({type:C.z.literal("ping")})]),ec=C.z.object({thinking:C.z.object({type:C.z.union([C.z.literal("enabled"),C.z.literal("disabled")]),budgetTokens:C.z.number().optional()}).optional()}),D=J("zod"),tc=D.z.object({command:D.z.string(),restart:D.z.boolean().optional()});function rc(r={}){return {type:"provider-defined",id:"anthropic.bash_20241022",args:{},parameters:tc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var nc=D.z.object({command:D.z.string(),restart:D.z.boolean().optional()});function oc(r={}){return {type:"provider-defined",id:"anthropic.bash_20250124",args:{},parameters:nc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var sc=D.z.object({command:D.z.enum(["view","create","str_replace","insert","undo_edit"]),path:D.z.string(),file_text:D.z.string().optional(),insert_line:D.z.number().int().optional(),new_str:D.z.string().optional(),old_str:D.z.string().optional(),view_range:D.z.array(D.z.number().int()).optional()});function ic(r={}){return {type:"provider-defined",id:"anthropic.text_editor_20241022",args:{},parameters:sc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var ac=D.z.object({command:D.z.enum(["view","create","str_replace","insert","undo_edit"]),path:D.z.string(),file_text:D.z.string().optional(),insert_line:D.z.number().int().optional(),new_str:D.z.string().optional(),old_str:D.z.string().optional(),view_range:D.z.array(D.z.number().int()).optional()});function lc(r={}){return {type:"provider-defined",id:"anthropic.text_editor_20250124",args:{},parameters:ac,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var uc=D.z.object({action:D.z.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:D.z.array(D.z.number().int()).optional(),text:D.z.string().optional()});function cc(r){return {type:"provider-defined",id:"anthropic.computer_20241022",args:{displayWidthPx:r.displayWidthPx,displayHeightPx:r.displayHeightPx,displayNumber:r.displayNumber},parameters:uc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var dc=D.z.object({action:D.z.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:D.z.tuple([D.z.number().int(),D.z.number().int()]).optional(),duration:D.z.number().optional(),scroll_amount:D.z.number().optional(),scroll_direction:D.z.enum(["up","down","left","right"]).optional(),start_coordinate:D.z.tuple([D.z.number().int(),D.z.number().int()]).optional(),text:D.z.string().optional()});function pc(r){return {type:"provider-defined",id:"anthropic.computer_20250124",args:{displayWidthPx:r.displayWidthPx,displayHeightPx:r.displayHeightPx,displayNumber:r.displayNumber},parameters:dc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var gc={bash_20241022:rc,bash_20250124:oc,textEditor_20241022:ic,textEditor_20250124:lc,computer_20241022:cc,computer_20250124:pc};function Uo(r={}){var e;let t=(e=(0, Do.withoutTrailingSlash)(r.baseURL))!=null?e:"https://api.anthropic.com/v1",n=()=>({"anthropic-version":"2023-06-01","x-api-key":(0, Do.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...r.headers}),o=(i,a={})=>new Yu(i,a,{provider:"anthropic.messages",baseURL:t,headers:n,fetch:r.fetch,supportsImageUrls:true}),s=function(i,a){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(i,a)};return s.languageModel=o,s.chat=o,s.messages=o,s.textEmbeddingModel=i=>{throw new Uu.NoSuchModelError({modelId:i,modelType:"textEmbeddingModel"})},s.tools=gc,s}var mc=Uo();});var ss=_e((af,os)=>{h();var Cr=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,hc=Object.getOwnPropertyNames,yc=Object.prototype.hasOwnProperty,vc=(r,e)=>{for(var t in e)Cr(r,t,{get:e[t],enumerable:true});},wc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of hc(e))!yc.call(r,o)&&o!==t&&Cr(r,o,{get:()=>e[o],enumerable:!(n=fc(e,o))||n.enumerable});return r},bc=r=>wc(Cr({},"__esModule",{value:true}),r),Zo={};vc(Zo,{createGoogleGenerativeAI:()=>ns,google:()=>Dc});os.exports=bc(Zo);var xr=G(),ye=G(),P=J("zod");function ee(r){if(_c(r))return;if(typeof r=="boolean")return {type:"boolean",properties:{}};let{type:e,description:t,required:n,properties:o,items:s,allOf:i,anyOf:a,oneOf:l,format:u,const:c,minLength:m,enum:p}=r,g={};if(t&&(g.description=t),n&&(g.required=n),u&&(g.format=u),c!==void 0&&(g.enum=[c]),e&&(Array.isArray(e)?e.includes("null")?(g.type=e.filter(v=>v!=="null")[0],g.nullable=true):g.type=e:e==="null"?g.type="null":g.type=e),p!==void 0&&(g.enum=p),o!=null&&(g.properties=Object.entries(o).reduce((v,[f,d])=>(v[f]=ee(d),v),{})),s&&(g.items=Array.isArray(s)?s.map(ee):ee(s)),i&&(g.allOf=i.map(ee)),a)if(a.some(v=>typeof v=="object"&&v?.type==="null")){let v=a.filter(f=>!(typeof f=="object"&&f?.type==="null"));if(v.length===1){let f=ee(v[0]);typeof f=="object"&&(g.nullable=true,Object.assign(g,f));}else g.anyOf=v.map(ee),g.nullable=true;}else g.anyOf=a.map(ee);return l&&(g.oneOf=l.map(ee)),m!==void 0&&(g.minLength=m),g}function _c(r){return r!=null&&typeof r=="object"&&r.type==="object"&&(r.properties==null||Object.keys(r.properties).length===0)&&!r.additionalProperties}var kr=q(),xc=G();function kc(r){var e,t;let n=[],o=[],s=true;for(let{role:i,content:a}of r)switch(i){case "system":{if(!s)throw new kr.UnsupportedFunctionalityError({functionality:"system messages are only supported at the beginning of the conversation"});n.push({text:a});break}case "user":{s=false;let l=[];for(let u of a)switch(u.type){case "text":{l.push({text:u.text});break}case "image":{l.push(u.image instanceof URL?{fileData:{mimeType:(e=u.mimeType)!=null?e:"image/jpeg",fileUri:u.image.toString()}}:{inlineData:{mimeType:(t=u.mimeType)!=null?t:"image/jpeg",data:(0, xc.convertUint8ArrayToBase64)(u.image)}});break}case "file":{l.push(u.data instanceof URL?{fileData:{mimeType:u.mimeType,fileUri:u.data.toString()}}:{inlineData:{mimeType:u.mimeType,data:u.data}});break}}o.push({role:"user",parts:l});break}case "assistant":{s=false,o.push({role:"model",parts:a.map(l=>{switch(l.type){case "text":return l.text.length===0?void 0:{text:l.text};case "file":{if(l.mimeType!=="image/png")throw new kr.UnsupportedFunctionalityError({functionality:"Only PNG images are supported in assistant messages"});if(l.data instanceof URL)throw new kr.UnsupportedFunctionalityError({functionality:"File data URLs in assistant messages are not supported"});return {inlineData:{mimeType:l.mimeType,data:l.data}}}case "tool-call":return {functionCall:{name:l.toolName,args:l.args}}}}).filter(l=>l!==void 0)});break}case "tool":{s=false,o.push({role:"user",parts:a.map(l=>({functionResponse:{name:l.toolName,response:{name:l.toolName,content:l.result}}}))});break}}return {systemInstruction:n.length>0?{parts:n}:void 0,contents:o}}function Jo(r){return r.includes("/")?r:`models/${r}`}var Rc=G(),Ze=J("zod"),Cc=Ze.z.object({error:Ze.z.object({code:Ze.z.number().nullable(),message:Ze.z.string(),status:Ze.z.string()})}),Rr=(0, Rc.createJsonErrorResponseHandler)({errorSchema:Cc,errorToMessage:r=>r.error.message}),Tc=q();function Pc(r,e,t,n){var o,s;let i=(o=r.tools)!=null&&o.length?r.tools:void 0,a=[],l=n.includes("gemini-2"),u=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(e)return {tools:l?{googleSearch:{}}:{googleSearchRetrieval:!u||!t?{}:{dynamicRetrievalConfig:t}},toolConfig:void 0,toolWarnings:a};if(i==null)return {tools:void 0,toolConfig:void 0,toolWarnings:a};let c=[];for(let g of i)g.type==="provider-defined"?a.push({type:"unsupported-tool",tool:g}):c.push({name:g.name,description:(s=g.description)!=null?s:"",parameters:ee(g.parameters)});let m=r.toolChoice;if(m==null)return {tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:a};let p=m.type;switch(p){case "auto":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:a};case "none":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:a};case "required":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:a};case "tool":return {tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[m.toolName]}},toolWarnings:a};default:{let g=p;throw new Tc.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${g}`})}}}function Vo({finishReason:r,hasToolCalls:e}){switch(r){case "STOP":return e?"tool-calls":"stop";case "MAX_TOKENS":return "length";case "IMAGE_SAFETY":case "RECITATION":case "SAFETY":case "BLOCKLIST":case "PROHIBITED_CONTENT":case "SPII":return "content-filter";case "FINISH_REASON_UNSPECIFIED":case "OTHER":return "other";case "MALFORMED_FUNCTION_CALL":return "error";default:return "unknown"}}var Ec=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode="json",this.supportsImageUrls=false,this.modelId=r,this.settings=e,this.config=t;}get supportsStructuredOutputs(){var r;return (r=this.settings.structuredOutputs)!=null?r:true}get provider(){return this.config.provider}async getArgs({mode:r,prompt:e,maxTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:c,providerMetadata:m}){var p,g,v;let f=r.type,d=[],y=(0, ye.parseProviderOptions)({provider:"google",providerOptions:m,schema:Oc});((p=y?.thinkingConfig)==null?void 0:p.includeThoughts)===true&&!this.config.provider.startsWith("google.vertex.")&&d.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let b={maxOutputTokens:t,temperature:n,topK:s,topP:o,frequencyPenalty:i,presencePenalty:a,stopSequences:l,seed:c,responseMimeType:u?.type==="json"?"application/json":void 0,responseSchema:u?.type==="json"&&u.schema!=null&&this.supportsStructuredOutputs?ee(u.schema):void 0,...this.settings.audioTimestamp&&{audioTimestamp:this.settings.audioTimestamp},responseModalities:y?.responseModalities,thinkingConfig:y?.thinkingConfig},{contents:k,systemInstruction:w}=kc(e);switch(f){case "regular":{let{tools:x,toolConfig:S,toolWarnings:z}=Pc(r,(g=this.settings.useSearchGrounding)!=null?g:false,this.settings.dynamicRetrievalConfig,this.modelId);return {args:{generationConfig:b,contents:k,systemInstruction:w,safetySettings:this.settings.safetySettings,tools:x,toolConfig:S,cachedContent:this.settings.cachedContent},warnings:[...d,...z]}}case "object-json":return {args:{generationConfig:{...b,responseMimeType:"application/json",responseSchema:r.schema!=null&&this.supportsStructuredOutputs?ee(r.schema):void 0},contents:k,systemInstruction:w,safetySettings:this.settings.safetySettings,cachedContent:this.settings.cachedContent},warnings:d};case "object-tool":return {args:{generationConfig:b,contents:k,systemInstruction:w,tools:{functionDeclarations:[{name:r.tool.name,description:(v=r.tool.description)!=null?v:"",parameters:ee(r.tool.parameters)}]},toolConfig:{functionCallingConfig:{mode:"ANY"}},safetySettings:this.settings.safetySettings,cachedContent:this.settings.cachedContent},warnings:d};default:{let x=f;throw new Error(`Unsupported type: ${x}`)}}}supportsUrl(r){return this.config.isSupportedUrl(r)}async doGenerate(r){var e,t,n,o,s;let{args:i,warnings:a}=await this.getArgs(r),l=JSON.stringify(i),u=(0, ye.combineHeaders)(await(0, ye.resolve)(this.config.headers),r.headers),{responseHeaders:c,value:m,rawValue:p}=await(0, ye.postJsonToApi)({url:`${this.config.baseURL}/${Jo(this.modelId)}:generateContent`,headers:u,body:i,failedResponseHandler:Rr,successfulResponseHandler:(0, ye.createJsonResponseHandler)(Sc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{contents:g,...v}=i,f=m.candidates[0],d=f.content==null||typeof f.content!="object"||!("parts"in f.content)?[]:f.content.parts,y=Go({parts:d,generateId:this.config.generateId}),b=m.usageMetadata;return {text:Ko(d),reasoning:Xo(d),files:(e=Yo(d))==null?void 0:e.map(k=>({data:k.inlineData.data,mimeType:k.inlineData.mimeType})),toolCalls:y,finishReason:Vo({finishReason:f.finishReason,hasToolCalls:y!=null&&y.length>0}),usage:{promptTokens:(t=b?.promptTokenCount)!=null?t:NaN,completionTokens:(n=b?.candidatesTokenCount)!=null?n:NaN},rawCall:{rawPrompt:g,rawSettings:v},rawResponse:{headers:c,body:p},warnings:a,providerMetadata:{google:{groundingMetadata:(o=f.groundingMetadata)!=null?o:null,safetyRatings:(s=f.safetyRatings)!=null?s:null}},sources:Qo({groundingMetadata:f.groundingMetadata,generateId:this.config.generateId}),request:{body:l}}}async doStream(r){let{args:e,warnings:t}=await this.getArgs(r),n=JSON.stringify(e),o=(0, ye.combineHeaders)(await(0, ye.resolve)(this.config.headers),r.headers),{responseHeaders:s,value:i}=await(0, ye.postJsonToApi)({url:`${this.config.baseURL}/${Jo(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:Rr,successfulResponseHandler:(0, ye.createEventSourceResponseHandler)(Ic),abortSignal:r.abortSignal,fetch:this.config.fetch}),{contents:a,...l}=e,u="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},m,p=this.config.generateId,g=false;return {stream:i.pipeThrough(new TransformStream({transform(v,f){var d,y,b,k,w,x;if(!v.success){f.enqueue({type:"error",error:v.error});return}let S=v.value,z=S.usageMetadata;z!=null&&(c={promptTokens:(d=z.promptTokenCount)!=null?d:NaN,completionTokens:(y=z.candidatesTokenCount)!=null?y:NaN});let R=(b=S.candidates)==null?void 0:b[0];if(R==null)return;let T=R.content;if(T!=null){let O=Ko(T.parts);O!=null&&f.enqueue({type:"text-delta",textDelta:O});let j=Xo(T.parts);if(j!=null)for(let L of j)f.enqueue({type:"reasoning",textDelta:L.text});let I=Yo(T.parts);if(I!=null)for(let L of I)f.enqueue({type:"file",mimeType:L.inlineData.mimeType,data:L.inlineData.data});let F=Go({parts:T.parts,generateId:p});if(F!=null)for(let L of F)f.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:L.toolCallId,toolName:L.toolName,argsTextDelta:L.args}),f.enqueue({type:"tool-call",toolCallType:"function",toolCallId:L.toolCallId,toolName:L.toolName,args:L.args}),g=true;}if(R.finishReason!=null){u=Vo({finishReason:R.finishReason,hasToolCalls:g});let O=(k=Qo({groundingMetadata:R.groundingMetadata,generateId:p}))!=null?k:[];for(let j of O)f.enqueue({type:"source",source:j});m={google:{groundingMetadata:(w=R.groundingMetadata)!=null?w:null,safetyRatings:(x=R.safetyRatings)!=null?x:null}};}},flush(v){v.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:m});}})),rawCall:{rawPrompt:a,rawSettings:l},rawResponse:{headers:s},warnings:t,request:{body:n}}}};function Go({parts:r,generateId:e}){let t=r?.filter(n=>"functionCall"in n);return t==null||t.length===0?void 0:t.map(n=>({toolCallType:"function",toolCallId:e(),toolName:n.functionCall.name,args:JSON.stringify(n.functionCall.args)}))}function Ko(r){let e=r?.filter(t=>"text"in t&&t.thought!==true);return e==null||e.length===0?void 0:e.map(t=>t.text).join("")}function Xo(r){let e=r?.filter(t=>"text"in t&&t.thought===true&&t.text!=null);return e==null||e.length===0?void 0:e.map(t=>({type:"text",text:t.text}))}function Yo(r){return r?.filter(e=>"inlineData"in e)}function Qo({groundingMetadata:r,generateId:e}){var t;return (t=r?.groundingChunks)==null?void 0:t.filter(n=>n.web!=null).map(n=>({sourceType:"url",id:e(),url:n.web.uri,title:n.web.title}))}var es=P.z.object({parts:P.z.array(P.z.union([P.z.object({functionCall:P.z.object({name:P.z.string(),args:P.z.unknown()})}),P.z.object({inlineData:P.z.object({mimeType:P.z.string(),data:P.z.string()})}),P.z.object({text:P.z.string().nullish(),thought:P.z.boolean().nullish()})])).nullish()}),Ac=P.z.object({web:P.z.object({uri:P.z.string(),title:P.z.string()}).nullish(),retrievedContext:P.z.object({uri:P.z.string(),title:P.z.string()}).nullish()}),ts=P.z.object({webSearchQueries:P.z.array(P.z.string()).nullish(),retrievalQueries:P.z.array(P.z.string()).nullish(),searchEntryPoint:P.z.object({renderedContent:P.z.string()}).nullish(),groundingChunks:P.z.array(Ac).nullish(),groundingSupports:P.z.array(P.z.object({segment:P.z.object({startIndex:P.z.number().nullish(),endIndex:P.z.number().nullish(),text:P.z.string().nullish()}),segment_text:P.z.string().nullish(),groundingChunkIndices:P.z.array(P.z.number()).nullish(),supportChunkIndices:P.z.array(P.z.number()).nullish(),confidenceScores:P.z.array(P.z.number()).nullish(),confidenceScore:P.z.array(P.z.number()).nullish()})).nullish(),retrievalMetadata:P.z.union([P.z.object({webDynamicRetrievalScore:P.z.number()}),P.z.object({})]).nullish()}),rs=P.z.object({category:P.z.string().nullish(),probability:P.z.string().nullish(),probabilityScore:P.z.number().nullish(),severity:P.z.string().nullish(),severityScore:P.z.number().nullish(),blocked:P.z.boolean().nullish()}),Sc=P.z.object({candidates:P.z.array(P.z.object({content:es.nullish().or(P.z.object({}).strict()),finishReason:P.z.string().nullish(),safetyRatings:P.z.array(rs).nullish(),groundingMetadata:ts.nullish()})),usageMetadata:P.z.object({promptTokenCount:P.z.number().nullish(),candidatesTokenCount:P.z.number().nullish(),totalTokenCount:P.z.number().nullish()}).nullish()}),Ic=P.z.object({candidates:P.z.array(P.z.object({content:es.nullish(),finishReason:P.z.string().nullish(),safetyRatings:P.z.array(rs).nullish(),groundingMetadata:ts.nullish()})).nullish(),usageMetadata:P.z.object({promptTokenCount:P.z.number().nullish(),candidatesTokenCount:P.z.number().nullish(),totalTokenCount:P.z.number().nullish()}).nullish()}),Oc=P.z.object({responseModalities:P.z.array(P.z.enum(["TEXT","IMAGE"])).nullish(),thinkingConfig:P.z.object({thinkingBudget:P.z.number().nullish(),includeThoughts:P.z.boolean().nullish()}).nullish()}),zc=q(),At=G(),et=J("zod"),Mc=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){return 2048}get supportsParallelCalls(){return true}async doEmbed({values:r,headers:e,abortSignal:t}){if(r.length>this.maxEmbeddingsPerCall)throw new zc.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:r});let n=(0, At.combineHeaders)(await(0, At.resolve)(this.config.headers),e),{responseHeaders:o,value:s}=await(0, At.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:n,body:{requests:r.map(i=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:i}]},outputDimensionality:this.settings.outputDimensionality,taskType:this.settings.taskType}))},failedResponseHandler:Rr,successfulResponseHandler:(0, At.createJsonResponseHandler)(jc),abortSignal:t,fetch:this.config.fetch});return {embeddings:s.embeddings.map(i=>i.values),usage:void 0,rawResponse:{headers:o}}}},jc=et.z.object({embeddings:et.z.array(et.z.object({values:et.z.array(et.z.number())}))});function Nc(r){return r.toString().startsWith("https://generativelanguage.googleapis.com/v1beta/files/")}function ns(r={}){var e;let t=(e=(0, xr.withoutTrailingSlash)(r.baseURL))!=null?e:"https://generativelanguage.googleapis.com/v1beta",n=()=>({"x-goog-api-key":(0, xr.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...r.headers}),o=(a,l={})=>{var u;return new Ec(a,l,{provider:"google.generative-ai",baseURL:t,headers:n,generateId:(u=r.generateId)!=null?u:xr.generateId,isSupportedUrl:Nc,fetch:r.fetch})},s=(a,l={})=>new Mc(a,l,{provider:"google.generative-ai",baseURL:t,headers:n,fetch:r.fetch}),i=function(a,l){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return o(a,l)};return i.languageModel=o,i.chat=o,i.generativeAI=o,i.embedding=s,i.textEmbedding=s,i.textEmbeddingModel=s,i}var Dc=ns();});var is,as;exports.VercelProviderRuntime=void 0;var Tr=oe(()=>{h();Re();is=10,as=50,exports.VercelProviderRuntime=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,n){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(n?.tools??[],s),a=this.createModel(n?.model),l=Math.min(n?.maxSteps??this.config.maxSteps??is,as);try{let u=0,c=await o({model:a,system:n?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:l,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:p=>{if(u++,!!n?.onOutput){if(p.toolCalls&&p.toolCalls.length>0)for(let g of p.toolCalls)n.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:g.toolCallId,name:g.toolName,input:g.args}]}}),"stdout");if(p.toolResults&&p.toolResults.length>0)for(let g of p.toolResults){let v=typeof g.result=="string"?g.result:JSON.stringify(g.result);n.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:g.toolCallId,output:v,is_error:!1}]}}),"stdout");}}}}),m=new Set((n?.tools??[]).filter(p=>!p.execute).map(p=>p.name));if(c.finishReason==="tool-calls"&&Array.isArray(c.toolCalls)&&c.toolCalls.length>0){let p=c.toolCalls.filter(g=>m.has(g.toolName));if(p.length>0){let g=p[0];throw new exports.ClientToolCallRequiredError({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e,responseMessages:c.response?.messages??[],toolDefinitions:n?.tools??[],maxSteps:l,systemPrompt:n?.systemPrompt,modelOverride:n?.model})}}if(n?.onUsage&&c.usage){let p={inputTokens:c.usage.promptTokens??0,outputTokens:c.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};n.onUsage(p);}return n?.onModel&&n.onModel(n.model??this.config.model),c.text??""}catch(u){throw u instanceof exports.ClientToolCallRequiredError?u:u.status===401?new exports.ProviderError(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):u.status===429?new exports.ProviderError(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new exports.ProviderError(`Provider error: ${u.message}`,this.config.provider)}}async continueWithToolResults(e,t,n){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),l=Math.min(e.maxSteps??this.config.maxSteps??is,as),u=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(c=>({type:"tool-result",toolCallId:c.toolCallId,toolName:c.toolName,result:typeof c.result=="string"?c.result:JSON.stringify(c.result)}))}];try{let c=await o({model:a,system:e.systemPrompt??void 0,messages:u,tools:i,maxSteps:l,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),m=new Set(e.toolDefinitions.filter(p=>!p.execute).map(p=>p.name));if(c.finishReason==="tool-calls"&&Array.isArray(c.toolCalls)&&c.toolCalls.length>0){let p=c.toolCalls.filter(g=>m.has(g.toolName));if(p.length>0){let g=p[0];throw new exports.ClientToolCallRequiredError({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(v=>({type:"tool-result",toolCallId:v.toolCallId,toolName:v.toolName,result:typeof v.result=="string"?v.result:JSON.stringify(v.result)}))},...c.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return n?.onUsage&&c.usage&&n.onUsage({inputTokens:c.usage.promptTokens??0,outputTokens:c.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),n?.onModel&&n.onModel(e.modelOverride??this.config.model),c.text??""}catch(c){throw c instanceof exports.ClientToolCallRequiredError?c:new exports.ProviderError(`Provider error: ${c.message}`,this.config.provider)}}convertTools(e,t){let{z:n}=J("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},n);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let n={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let l;switch(a.type){case "string":l=t.string();break;case "number":l=t.number();break;case "integer":l=t.number().int();break;case "boolean":l=t.boolean();break;case "array":l=t.array(t.any());break;default:l=t.any();}a.description&&(l=l.describe(a.description)),s.includes(i)||(l=l.optional()),n[i]=l;}return t.object(n)}createModel(e){let{provider:t,apiKey:n,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=br();return i({apiKey:n||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=br();return i({apiKey:n||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=Wo();return i({apiKey:n||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=ss();return i({apiKey:n||process.env.GOOGLE_API_KEY})(s)}default:throw new exports.ProviderError(`Unsupported API provider: ${t}`,t)}}};});var us={};zt(us,{registerApiProviders:()=>ls});function ls(r){Ie("api",(e,t)=>{let n=r?.apiKeys?.[e];return new exports.VercelProviderRuntime({provider:t,model:"",apiKey:n,maxSteps:r?.defaults?.maxSteps,temperature:r?.defaults?.temperature})});}var Pr=oe(()=>{h();Re();Tr();});function $c(r){if(!r)return r;let e=r.trim().replace(/\/+$/,"");return e.toLowerCase().endsWith("/mcp")?e.slice(0,-4):e}exports.McpHttpTransport=void 0;var Er=oe(()=>{h();exports.McpHttpTransport=class{endpoint;headers;timeoutMs;constructor(e){let t=$c(e.url);this.endpoint=`${t}/mcp`,this.headers={"Content-Type":"application/json",...e.headers??{}},e.apiKey&&(this.headers.Authorization=`Bearer ${e.apiKey}`),this.timeoutMs=e.timeoutMs??3e4;}async send(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{let o=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(e),signal:t.signal});if(clearTimeout(n),!o.ok){let a=await o.text();throw new Error(`HTTP ${o.status}: ${o.statusText}${a?` - ${a}`:""}`)}let s=o.headers.get("content-type");if(s?.includes("application/json"))return await o.json();let i=await o.text();return {jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Unexpected response content-type: ${s}`,data:i}}}catch(o){throw clearTimeout(n),o instanceof Error&&o.name==="AbortError"?new Error(`MCP-HTTP request timeout after ${this.timeoutMs}ms to ${this.endpoint}`):o}}async close(){}};});exports.RemoteAgentManager=void 0;var Ar=oe(()=>{h();Er();exports.RemoteAgentManager=class{logger;configs=new Map;transports=new Map;constructor(e={}){this.logger=e.logger??(()=>{});}loadConfig(e,t){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,new exports.McpHttpTransport({url:t.url,apiKey:t.apiKey,headers:t.headers,timeoutMs:t.timeoutMs})),this.logger(`Loaded remote agent config for: ${e}`,"debug");}loadConfigWithTransport(e,t,n){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,n),this.logger(`Loaded remote agent config for: ${e} (custom transport)`,"debug");}getConfig(e){return this.configs.get(e)}isRemoteAgent(e){return this.configs.has(e)}getRemoteAgentIds(){return Array.from(this.configs.keys())}async query(e,t){let n=this.requireConfig(e),o=n.tools?.query??"crewx_queryAgent",i={agentId:n.agentId??e,query:t.query};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,o,i);return this.normalizeResponse(a)}catch(a){let l=a instanceof Error?a.message:String(a);throw this.logger(`Remote query failed for agent ${e}: ${l}`,"error"),a}}async execute(e,t){let n=this.requireConfig(e),o=n.tools?.execute??"crewx_executeAgent",i={agentId:n.agentId??e,task:t.task};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,o,i);return this.normalizeResponse(a)}catch(a){let l=a instanceof Error?a.message:String(a);throw this.logger(`Remote execute failed for agent ${e}: ${l}`,"error"),a}}mapToolNames(e,t){let n=this.requireConfig(e);n.tools={query:t.query??n.tools?.query??"crewx_queryAgent",execute:t.execute??n.tools?.execute??"crewx_executeAgent"},this.logger(`Updated tool name mapping for agent ${e}`,"debug");}async clearConfigs(){for(let e of this.transports.values())await e.close();this.configs.clear(),this.transports.clear(),this.logger("Cleared all remote agent configurations","debug");}requireConfig(e){let t=this.configs.get(e);if(!t)throw new Error(`Agent ${e} is not configured as a remote agent`);return t}async callRemoteTool(e,t,n){let o=this.transports.get(e);if(!o)throw new Error(`No transport available for agent ${e}`);let s={jsonrpc:"2.0",id:`${t}-${Date.now()}`,method:"tools/call",params:{name:t,arguments:n}};this.logger(`Calling remote MCP tool ${t} for agent ${e}`,"debug");let i=await o.send(s);if(i.error)throw new Error(i.error.message||"MCP server returned an error");return i.result}normalizeResponse(e){if(!e)return {success:false,content:[{type:"text",text:"Remote agent returned no response."}]};let t=e;if(Array.isArray(t.content)&&t.content.length>0)return t;let n=t.response??t.implementation??t.message??t.output,o=typeof n=="string"?n:JSON.stringify(n??e,null,2);return {...t,content:[{type:"text",text:o}]}}validateConfig(e){if(!e.url)throw new Error("Remote agent configuration requires a URL");if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("Remote agent URL must start with http:// or https://");if(e.type!=="mcp-http")throw new Error(`Unsupported remote agent type: ${e.type}`)}};});var ds={};zt(ds,{RemoteProviderRuntime:()=>exports.RemoteProviderRuntime,createRemoteProviderFactory:()=>cs,resolveFileRemoteAgent:()=>Jc});function Bc(r){let e=fs$1.readFileSync(r,"utf-8"),t=jsYaml.load(e);return {agents:Array.isArray(t?.agents)?t.agents:void 0}}function Wc(r){let e=Array.isArray(r.provider)?r.provider[0]:r.provider;return e||(Array.isArray(r.inline?.provider)?r.inline.provider[0]:r.inline?.provider)}function Jc(r,e=Bc,t=fs$1.existsSync){let n=r.location.replace("file://","");if(!t(n))throw new Error(`Remote config file not found: ${n}`);if(!r.external_agent_id)throw new Error(`external_agent_id is required for file:// remote provider "${r.id}"`);let s=e(n).agents?.find(l=>l.id===r.external_agent_id);if(!s)throw new Error(`Agent "${r.external_agent_id}" not found in ${n}`);let i=Wc(s);if(!i)throw new Error(`Agent "${r.external_agent_id}" in ${n} has no provider configured`);if(i.startsWith("remote/"))throw new Error(`Chained remotes not allowed: ${r.id} \u2192 ${i}`);let a=X.resolve(X.dirname(n),s.working_directory??".");return {agent:{...s,working_directory:a},provider:i}}function cs(r,e=pe){return (t,n)=>{let o=r.get(t);if(!o)throw new Error(`Remote provider "${t}" not found. Available: ${Array.from(r.keys()).join(", ")||"(none)"}`);if(o.location.startsWith("file://"))throw new Error(`Remote provider "${t}" uses file:// location which is not supported at the SDK level. Use the CLI commands (crewx query / crewx execute) which handle file:// remotes automatically.`);return new exports.RemoteProviderRuntime(t,o,e)}}function Vc(r,e){let t=e.location;if(!t)throw new Error("Remote provider config requires a location");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Unsupported remote location protocol for MCP-HTTP: ${t}`);return {type:"mcp-http",url:t,apiKey:e.apiKey,headers:e.headers,timeoutMs:e.timeout?.query??3e4,agentId:e.external_agent_id??r}}exports.RemoteProviderRuntime=void 0;var Sr=oe(()=>{h();Re();Ar();exports.RemoteProviderRuntime=class{manager;agentId;constructor(e,t,n=pe){this.agentId=t.external_agent_id??e,this.manager=new exports.RemoteAgentManager;let o=Vc(e,t);this.manager.loadConfig(this.agentId,o);}async query(e,t){return (await this.manager.query(this.agentId,{agentId:this.agentId,query:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(o=>o.text).join(`
34
34
  `)}async execute(e,t){return (await this.manager.execute(this.agentId,{agentId:this.agentId,task:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(o=>o.text).join(`
35
- `)}};});var us={};zt(us,{PluginProviderRuntime:()=>exports.PluginProviderRuntime,createPluginProviderFactory:()=>ls});function ls(r){return (e,t)=>{let n=r.get(e);if(!n)throw new exports.ProviderError(`Plugin provider "${e}" not found. Available: ${Array.from(r.keys()).join(", ")||"(none)"}`,`plugin/${e}`);return new exports.PluginProviderRuntime(e,n)}}function is(r,e,t,n){let o=r.map(s=>s.replace(/\{model\}/g,e));return n&&o.push(t),o}function Fc(r){if(!r||typeof r!="string")throw new Error("Plugin provider requires a cli_command")}function as(r){if(!Array.isArray(r))throw new Error("CLI arguments must be an array");for(let e of r)if(typeof e!="string")throw new Error("Each CLI argument must be a string")}function Uc(r){for(let{pattern:e}of r)if(typeof e!="string")throw new Error("Error pattern must be a string")}function Bc(r){for(let[e,t]of Object.entries(r))if(typeof e!="string"||typeof t!="string")throw new Error("env entries must be string key/value pairs")}exports.PluginProviderRuntime=void 0;var Pr=oe(()=>{y();Re();ft();exports.PluginProviderRuntime=class{constructor(e,t){this.config=t;this.providerStr=`plugin/${e}`,Fc(t.cli_command),as(t.query_args),as(t.execute_args),t.error_patterns&&Uc(t.error_patterns),t.env&&Bc(t.env);}config;providerStr;async query(e,t){let n=t?.model??this.config.default_model??"default",o=is(this.config.query_args,n,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${o.join(" ")}`);let i=this.config.timeout?.query??6e5;return this.runProcess(o,t,s,i)}async execute(e,t){let n=t?.model??this.config.default_model??"default",o=is(this.config.execute_args,n,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${o.join(" ")}`);let i=this.config.timeout?.execute??6e5;return this.runProcess(o,t,s,i)}runProcess(e,t,n,o){return new Promise((s,i)=>{let a={...process.env,...this.config.env??{}},l=je({command:this.config.cli_command,allowShellFallback:true}),u=Ne(l,e),c=child_process.spawn(u.command,u.argv,{env:a,shell:u.shell??false,stdio:["pipe","pipe","pipe"],windowsHide:u.windowsHide});n!==void 0&&c.stdin.write(n),c.stdin.end(),c.pid!==void 0&&t?.onPid?.(c.pid);let p="",g="",m="",v="";c.stdout.on("data",d=>{let h=d.toString();p+=h,m+=h;let _=m.split(`
36
- `);m=_.pop()??"";for(let C of _)C.trim()&&t?.onOutput?.(C,"stdout");}),c.stderr.on("data",d=>{let h=d.toString();g+=h,v+=h;let _=v.split(`
37
- `);v=_.pop()??"";for(let C of _)C.trim()&&t?.onOutput?.(C,"stderr");});let f=setTimeout(()=>{c.kill("SIGTERM"),i(new exports.ProviderError(`Plugin provider "${this.providerStr}" timed out after ${o}ms`,this.providerStr));},o);c.on("error",d=>{if(clearTimeout(f),d.code==="ENOENT"){let h=this.config.not_installed_message??`CLI command "${this.config.cli_command}" not found. Is ${this.config.id} installed?`;i(new exports.ProviderError(h,this.providerStr));}else i(new exports.ProviderError(`Spawn error: ${d.message}`,this.providerStr));}),c.on("close",d=>{clearTimeout(f),m.trim()&&t?.onOutput?.(m,"stdout"),v.trim()&&t?.onOutput?.(v,"stderr");let h=d??0;if(t?.onExitCode?.(h),this.config.error_patterns){let _=g||p;for(let C of this.config.error_patterns)if(_.includes(C.pattern)){i(new exports.ProviderError(C.message,this.providerStr));return}}if(d!==0){i(new exports.ProviderError(`Process exited with code ${d}: ${g.slice(0,500)}`,this.providerStr));return}s(p.trim());});})}};});y();y();y();function Os(r){let e=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=r.split("/").map(o=>o==="**"?".*":o.split("*").map(e).join("[^/]*"));return new RegExp(`^${n.join("\\/")}$`)}function se(r,e){try{return Os(e).test(r)}catch{return false}}y();y();var zs=zod.z.object({model:zod.z.string().optional(),system_prompt:zod.z.string().optional(),prompt:zod.z.string().optional(),layout:zod.z.union([zod.z.string(),zod.z.object({id:zod.z.string(),props:zod.z.record(zod.z.unknown()).optional()}),zod.z.object({props:zod.z.record(zod.z.unknown())}),zod.z.object({template:zod.z.string()})]).optional()}).catchall(zod.z.unknown()),Ms=zod.z.object({id:zod.z.string(),name:zod.z.string().optional(),role:zod.z.string().optional(),team:zod.z.string().optional(),provider:zod.z.union([zod.z.string(),zod.z.array(zod.z.string())]),working_directory:zod.z.string().optional(),description:zod.z.string().optional(),tags:zod.z.array(zod.z.string()).optional(),inline:zs.optional()}).catchall(zod.z.unknown()),Hr=zod.z.object({agents:zod.z.array(Ms).optional(),hooks:zod.z.array(zod.z.unknown()).optional(),settings:zod.z.record(zod.z.unknown()).optional(),skills:zod.z.unknown().optional(),layouts:zod.z.record(zod.z.unknown()).optional(),documents:zod.z.record(zod.z.unknown()).optional()}).catchall(zod.z.unknown());var xe=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="ConfigLoadError";}cause};function ut(r){if(!r||typeof r!="string"||!r.trim())throw new xe("YAML content must be a non-empty string");let e;try{e=jsYaml.load(r);}catch(o){throw new xe(`YAML parse error: ${o.message}`,o)}let t=$s(e),n=Hr.safeParse(t);if(!n.success)throw new xe(`Config validation error: ${n.error.message}`);return n.data}function ct(r){let e;try{e=fs$1.readFileSync(r,"utf-8");}catch(t){throw new xe(`Cannot read file: ${r}`,t)}return ut(e)}function $s(r){if(!r||typeof r!="object")return {agents:[]};let e=r,t;if(e.agents&&typeof e.agents=="object"&&!Array.isArray(e.agents)){let o=e.agents;t=Object.entries(o).map(([s,i])=>({id:s,...i&&typeof i=="object"?i:{}}));}else if(Array.isArray(e.agents))t=e.agents;else return {...e,agents:[]};let n=t.map(o=>{if(o.provider===void 0&&o.inline&&typeof o.inline=="object"){let s=o.inline;if(s.provider!==void 0)return {...o,provider:s.provider}}return o});return {...e,agents:n}}y();var ke=X.join("templates","agents");function Ls(){try{let e=(typeof U=="function"?U:module$1.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")).resolve("@crewx/sdk/package.json");return X.dirname(e)}catch{return null}}function Se(r){if(r&&fs$1.existsSync(r))return r;let e=process.env.CREWX_SDK_TEMPLATES_PATH;if(e&&fs$1.existsSync(e))return e;let t=Ls();if(t){let o=X.join(t,ke);if(fs$1.existsSync(o))return o}let n=[X.join(__dirname,"..",ke),X.join(__dirname,"..","..",ke),X.join(__dirname,"..","..","..",ke),X.join(process.cwd(),"packages","sdk",ke),X.join(process.cwd(),ke)];for(let o of n)if(fs$1.existsSync(o))return o;throw new Error(`[@crewx/sdk] Templates directory not found.
35
+ `)}};});var fs={};zt(fs,{PluginProviderRuntime:()=>exports.PluginProviderRuntime,createPluginProviderFactory:()=>ms});function ms(r){return (e,t)=>{let n=r.get(e);if(!n)throw new exports.ProviderError(`Plugin provider "${e}" not found. Available: ${Array.from(r.keys()).join(", ")||"(none)"}`,`plugin/${e}`);return new exports.PluginProviderRuntime(e,n)}}function ps(r,e,t,n){let o=r.map(s=>s.replace(/\{model\}/g,e));return n&&o.push(t),o}function Kc(r){if(!r||typeof r!="string")throw new Error("Plugin provider requires a cli_command")}function gs(r){if(!Array.isArray(r))throw new Error("CLI arguments must be an array");for(let e of r)if(typeof e!="string")throw new Error("Each CLI argument must be a string")}function Xc(r){for(let{pattern:e}of r)if(typeof e!="string")throw new Error("Error pattern must be a string")}function Yc(r){for(let[e,t]of Object.entries(r))if(typeof e!="string"||typeof t!="string")throw new Error("env entries must be string key/value pairs")}exports.PluginProviderRuntime=void 0;var Ir=oe(()=>{h();Re();ft();exports.PluginProviderRuntime=class{constructor(e,t){this.config=t;this.providerStr=`plugin/${e}`,Kc(t.cli_command),gs(t.query_args),gs(t.execute_args),t.error_patterns&&Xc(t.error_patterns),t.env&&Yc(t.env);}config;providerStr;async query(e,t){let n=t?.model??this.config.default_model??"default",o=ps(this.config.query_args,n,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${o.join(" ")}`);let i=this.config.timeout?.query??6e5;return this.runProcess(o,t,s,i)}async execute(e,t){let n=t?.model??this.config.default_model??"default",o=ps(this.config.execute_args,n,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${o.join(" ")}`);let i=this.config.timeout?.execute??6e5;return this.runProcess(o,t,s,i)}runProcess(e,t,n,o){return new Promise((s,i)=>{let a={...process.env,...this.config.env??{}},l=je({command:this.config.cli_command,allowShellFallback:true}),u=Ne(l,e),c=child_process.spawn(u.command,u.argv,{env:a,shell:u.shell??false,stdio:["pipe","pipe","pipe"],windowsHide:u.windowsHide});n!==void 0&&c.stdin.write(n),c.stdin.end(),c.pid!==void 0&&t?.onPid?.(c.pid);let m="",p="",g="",v="";c.stdout.on("data",d=>{let y=d.toString();m+=y,g+=y;let b=g.split(`
36
+ `);g=b.pop()??"";for(let k of b)k.trim()&&t?.onOutput?.(k,"stdout");}),c.stderr.on("data",d=>{let y=d.toString();p+=y,v+=y;let b=v.split(`
37
+ `);v=b.pop()??"";for(let k of b)k.trim()&&t?.onOutput?.(k,"stderr");});let f=setTimeout(()=>{c.kill("SIGTERM"),i(new exports.ProviderError(`Plugin provider "${this.providerStr}" timed out after ${o}ms`,this.providerStr));},o);c.on("error",d=>{if(clearTimeout(f),d.code==="ENOENT"){let y=this.config.not_installed_message??`CLI command "${this.config.cli_command}" not found. Is ${this.config.id} installed?`;i(new exports.ProviderError(y,this.providerStr));}else i(new exports.ProviderError(`Spawn error: ${d.message}`,this.providerStr));}),c.on("close",d=>{clearTimeout(f),g.trim()&&t?.onOutput?.(g,"stdout"),v.trim()&&t?.onOutput?.(v,"stderr");let y=d??0;if(t?.onExitCode?.(y),this.config.error_patterns){let b=p||m;for(let k of this.config.error_patterns)if(b.includes(k.pattern)){i(new exports.ProviderError(k.message,this.providerStr));return}}if(d!==0){i(new exports.ProviderError(`Process exited with code ${d}: ${p.slice(0,500)}`,this.providerStr));return}s(m.trim());});})}};});h();h();h();function $s(r){let e=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=r.split("/").map(o=>o==="**"?".*":o.split("*").map(e).join("[^/]*"));return new RegExp(`^${n.join("\\/")}$`)}function se(r,e){try{return $s(e).test(r)}catch{return false}}h();h();var Hs=zod.z.object({model:zod.z.string().optional(),system_prompt:zod.z.string().optional(),prompt:zod.z.string().optional(),layout:zod.z.union([zod.z.string(),zod.z.object({id:zod.z.string(),props:zod.z.record(zod.z.unknown()).optional()}),zod.z.object({props:zod.z.record(zod.z.unknown())}),zod.z.object({template:zod.z.string()})]).optional()}).catchall(zod.z.unknown()),Ur=zod.z.object({include:zod.z.array(zod.z.string()).optional()}).optional(),Ls=zod.z.object({id:zod.z.string(),name:zod.z.string().optional(),role:zod.z.string().optional(),team:zod.z.string().optional(),provider:zod.z.union([zod.z.string(),zod.z.array(zod.z.string())]),working_directory:zod.z.string().optional(),description:zod.z.string().optional(),tags:zod.z.array(zod.z.string()).optional(),inline:Hs.optional(),timeoutMs:zod.z.number().optional(),idleTimeoutMs:zod.z.number().optional(),skills:Ur}).catchall(zod.z.unknown()),Br=zod.z.object({agents:zod.z.array(Ls).optional(),hooks:zod.z.array(zod.z.unknown()).optional(),settings:zod.z.record(zod.z.unknown()).optional(),skills:zod.z.unknown().optional(),layouts:zod.z.record(zod.z.unknown()).optional(),documents:zod.z.record(zod.z.unknown()).optional()}).catchall(zod.z.unknown());var xe=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="ConfigLoadError";}cause};function ut(r){if(!r||typeof r!="string"||!r.trim())throw new xe("YAML content must be a non-empty string");let e;try{e=jsYaml.load(r);}catch(o){throw new xe(`YAML parse error: ${o.message}`,o)}let t=Us(e),n=Br.safeParse(t);if(!n.success)throw new xe(`Config validation error: ${n.error.message}`);return n.data}function ct(r){let e;try{e=fs$1.readFileSync(r,"utf-8");}catch(t){throw new xe(`Cannot read file: ${r}`,t)}return ut(e)}function Us(r){if(!r||typeof r!="object")return {agents:[]};let e=r,t;if(e.agents&&typeof e.agents=="object"&&!Array.isArray(e.agents)){let o=e.agents;t=Object.entries(o).map(([s,i])=>({id:s,...i&&typeof i=="object"?i:{}}));}else if(Array.isArray(e.agents))t=e.agents;else return {...e,agents:[]};let n=t.map(o=>{if(o.provider===void 0&&o.inline&&typeof o.inline=="object"){let s=o.inline;if(s.provider!==void 0)return {...o,provider:s.provider}}return o});return {...e,agents:n}}h();var ke=X.join("templates","agents");function Js(){try{let e=(typeof J=="function"?J:module$1.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")).resolve("@crewx/sdk/package.json");return X.dirname(e)}catch{return null}}function Se(r){if(r&&fs$1.existsSync(r))return r;let e=process.env.CREWX_SDK_TEMPLATES_PATH;if(e&&fs$1.existsSync(e))return e;let t=Js();if(t){let o=X.join(t,ke);if(fs$1.existsSync(o))return o}let n=[X.join(__dirname,"..",ke),X.join(__dirname,"..","..",ke),X.join(__dirname,"..","..","..",ke),X.join(process.cwd(),"packages","sdk",ke),X.join(process.cwd(),ke)];for(let o of n)if(fs$1.existsSync(o))return o;throw new Error(`[@crewx/sdk] Templates directory not found.
38
38
  `+(t?` package anchor: ${X.join(t,ke)}
39
39
  `:` package anchor: (unresolved)
40
40
  `)+n.map(o=>` candidate: ${o}`).join(`
41
41
  `)+`
42
- Set CREWX_SDK_TEMPLATES_PATH or pass options.templatesPath.`)}function Mt(){let r=Se();return {yamlPath:X.join(r,"default.yaml"),dir:r}}y();var de=class extends Error{constructor(e,t){let n=t.length>0?` Available: ${t.join(", ")}`:"";super(`Agent not found: "${e}".${n}`),this.name="AgentNotFoundError";}},qs={claude:{id:"claude",provider:"cli/claude"},gemini:{id:"gemini",provider:"cli/gemini"},copilot:{id:"copilot",provider:"cli/copilot"},codex:{id:"codex",provider:"cli/codex"}};function pt(r,e){let t=r.startsWith("@")?r.slice(1):r,n=e.find(s=>s.id===t);if(n)return n;let o=qs[t];if(o)return o;throw new de(r,e.map(s=>s.id))}Re();y();y();var ti=[/^ANTHROPIC_/i,/^OPENAI_/i,/^AWS_SECRET/i,/^SLACK_/i,/^GITHUB_TOKEN$/i,/^CREWX_MCP_KEY$/i,/^DATABASE_/i,/^AWS_ACCESS_KEY/i,/^AWS_SESSION_TOKEN$/i,/^GH_TOKEN$/i,/^GH_APP_/i,/^NPM_TOKEN$/i,/^NPM_AUTH/i,/^GOOGLE_APPLICATION/i,/^GCLOUD_/i,/^AZURE_/i,/^ARM_/i,/^DOCKER_PASSWORD$/i,/^DOCKER_AUTH/i,/^SSH_PRIVATE/i,/^SSH_AUTH_SOCK$/i,/^CI_JOB_TOKEN$/i,/^ACTIONS_RUNTIME_TOKEN$/i,/^VAULT_TOKEN$/i,/^SONAR_TOKEN$/i,/^CODECOV_TOKEN$/i,/TOKEN$/i,/SECRET$/i,/PASSWORD$/i,/API_KEY$/i],ri=/[;|&`$(){}!><\n\r]/,ni=2,oi=["*","**","*:*","* *","**/*"];function si(){let r={};for(let[e,t]of Object.entries(process.env))t!==void 0&&(ti.some(n=>n.test(e))||(r[e]=t));return r}function ii(r){if(ri.test(r))throw new Error(`exec blocked: shell metacharacter detected in "${r}"`)}function ai(r){return /^npx\s+@crewx\/[\w-]+/.test(r)}function li(r){if(oi.includes(r.trim()))throw new Error(`exec config error: overly broad pattern "${r}" is not allowed`);if(!/^[\w./@-]/.test(r))throw new Error("exec config error: pattern must start with a command name")}function ui(r,e){let t=e.allow??[],n=e.deny??[];for(let o of [...t,...n])li(o);return n.some(o=>se(r,o))?false:ai(r)?true:t.some(o=>se(r,o))}var Br=false;function ci(r){Br=r;}function $e(r){if(!Br)return;let e=JSON.stringify({span:"template_exec",...r,timestamp:new Date().toISOString()});console.error(e);}function di(r){let e=[],t="",n=false,o=false;for(let s=0;s<r.length;s++){let i=r[s];i==="'"&&!o?n=!n:i==='"'&&!n?o=!o:i===" "&&!n&&!o?t.length>0&&(e.push(t),t=""):t+=i;}return t.length>0&&e.push(t),e}function Wr(r,e){let t=Date.now(),n=parseInt(process.env.CREWX_EXEC_DEPTH??"0",10);if(isNaN(n)||n>=ni)return $e({command:r,status:"denied",reason:"invalid or max recursion depth"}),"(exec blocked: max recursion depth reached)";try{ii(r);}catch{return $e({command:r,status:"denied",reason:"shell metacharacter detected"}),`(exec blocked: shell metacharacter detected in "${r}")`}if(!ui(r,e))return $e({command:r,status:"denied",reason:"not in allow list"}),`(exec blocked: ${r})`;try{let o=di(r),[s,...i]=o;if(!s)return `(exec failed: ${r})`;let a=si(),l=child_process.execFileSync(s,i,{timeout:e.timeout??5e3,maxBuffer:64*1024,encoding:"utf-8",env:{...a,CREWX_EXEC_DEPTH:String(n+1)},stdio:["pipe","pipe","pipe"]}),u=Date.now()-t;return $e({command:r,status:"allowed",allowed_by:"policy",duration_ms:u}),`<exec-output cmd="${r}">
42
+ Set CREWX_SDK_TEMPLATES_PATH or pass options.templatesPath.`)}function Mt(){let r=Se();return {yamlPath:X.join(r,"default.yaml"),dir:r}}h();var de=class extends Error{constructor(e,t){let n=t.length>0?` Available: ${t.join(", ")}`:"";super(`Agent not found: "${e}".${n}`),this.name="AgentNotFoundError";}},Vs={claude:{id:"claude",provider:"cli/claude"},gemini:{id:"gemini",provider:"cli/gemini"},copilot:{id:"copilot",provider:"cli/copilot"},codex:{id:"codex",provider:"cli/codex"}};function pt(r,e){let t=r.startsWith("@")?r.slice(1):r,n=e.find(s=>s.id===t);if(n)return n;let o=Vs[t];if(o)return o;throw new de(r,e.map(s=>s.id))}Re();h();var Lt={totalMs:72e5,idleMs:6e5,killGraceMs:2e3};function qt(r,e){if(r===void 0||r==="")return e;let t=parseInt(r,10);return Number.isNaN(t)?e:t}function Kr(r=process.env){return {totalMs:qt(r.CREWX_TIMEOUT_MS,Lt.totalMs),idleMs:qt(r.CREWX_IDLE_TIMEOUT_MS,Lt.idleMs),killGraceMs:qt(r.CREWX_KILL_GRACE_MS,Lt.killGraceMs)}}h();h();var li=[/^ANTHROPIC_/i,/^OPENAI_/i,/^AWS_SECRET/i,/^SLACK_/i,/^GITHUB_TOKEN$/i,/^CREWX_MCP_KEY$/i,/^DATABASE_/i,/^AWS_ACCESS_KEY/i,/^AWS_SESSION_TOKEN$/i,/^GH_TOKEN$/i,/^GH_APP_/i,/^NPM_TOKEN$/i,/^NPM_AUTH/i,/^GOOGLE_APPLICATION/i,/^GCLOUD_/i,/^AZURE_/i,/^ARM_/i,/^DOCKER_PASSWORD$/i,/^DOCKER_AUTH/i,/^SSH_PRIVATE/i,/^SSH_AUTH_SOCK$/i,/^CI_JOB_TOKEN$/i,/^ACTIONS_RUNTIME_TOKEN$/i,/^VAULT_TOKEN$/i,/^SONAR_TOKEN$/i,/^CODECOV_TOKEN$/i,/TOKEN$/i,/SECRET$/i,/PASSWORD$/i,/API_KEY$/i],ui=/[;|&`$(){}!><\n\r]/,ci=2,di=["*","**","*:*","* *","**/*"];function pi(){let r={};for(let[e,t]of Object.entries(process.env))t!==void 0&&(li.some(n=>n.test(e))||(r[e]=t));return r}function gi(r){if(ui.test(r))throw new Error(`exec blocked: shell metacharacter detected in "${r}"`)}function mi(r){return /^npx\s+@crewx\/[\w-]+/.test(r)}function fi(r){if(di.includes(r.trim()))throw new Error(`exec config error: overly broad pattern "${r}" is not allowed`);if(!/^[\w./@-]/.test(r))throw new Error("exec config error: pattern must start with a command name")}function hi(r,e){let t=e.allow??[],n=e.deny??[];for(let o of [...t,...n])fi(o);return n.some(o=>se(r,o))?false:mi(r)?true:t.some(o=>se(r,o))}var Xr=false;function yi(r){Xr=r;}function De(r){if(!Xr)return;let e=JSON.stringify({span:"template_exec",...r,timestamp:new Date().toISOString()});console.error(e);}function vi(r){let e=[],t="",n=false,o=false;for(let s=0;s<r.length;s++){let i=r[s];i==="'"&&!o?n=!n:i==='"'&&!n?o=!o:i===" "&&!n&&!o?t.length>0&&(e.push(t),t=""):t+=i;}return t.length>0&&e.push(t),e}function Yr(r,e){let t=Date.now(),n=parseInt(process.env.CREWX_EXEC_DEPTH??"0",10);if(isNaN(n)||n>=ci)return De({command:r,status:"denied",reason:"invalid or max recursion depth"}),"(exec blocked: max recursion depth reached)";try{gi(r);}catch{return De({command:r,status:"denied",reason:"shell metacharacter detected"}),`(exec blocked: shell metacharacter detected in "${r}")`}if(!hi(r,e))return De({command:r,status:"denied",reason:"not in allow list"}),`(exec blocked: ${r})`;try{let o=vi(r),[s,...i]=o;if(!s)return `(exec failed: ${r})`;let a=pi(),l=child_process.execFileSync(s,i,{timeout:e.timeout??5e3,maxBuffer:64*1024,encoding:"utf-8",env:{...a,CREWX_EXEC_DEPTH:String(n+1)},stdio:["pipe","pipe","pipe"]}),u=Date.now()-t;return De({command:r,status:"allowed",allowed_by:"policy",duration_ms:u}),`<exec-output cmd="${r}">
43
43
  ${l.trim()}
44
- </exec-output>`}catch{return $e({command:r,status:"error",reason:"execution failed"}),`(exec failed: ${r})`}}y();function Jr(r){return r==null?"":String(r)}y();function Vr(r,e){return `\`\`\`${e?.hash?.lang??""}
44
+ </exec-output>`}catch{return De({command:r,status:"error",reason:"execution failed"}),`(exec failed: ${r})`}}h();function Qr(r){return r==null?"":String(r)}h();function Zr(r,e){return `\`\`\`${e?.hash?.lang??""}
45
45
  ${r??""}
46
- \`\`\``}y();function Dt(r,e){if(!r)return "";if(r.length<=e)return r;let t=r.length-e;return `${r.substring(0,e)} (...+${t} chars)`}function Ht(r){return Array.isArray(r)||typeof r=="string"?r.length:0}function Lt(r){return typeof r!="string"?"":r.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}var Kr=["B","KB","MB","GB"];function qt(r){if(r===0)return "0 B";let e=Math.min(Math.floor(Math.log(r)/Math.log(1024)),Kr.length-1);return `${Math.round(r/Math.pow(1024,e)*100)/100} ${Kr[e]}`}function Ft(r){if(!r)return "";try{let e=r instanceof Date?r:new Date(r);return isNaN(e.getTime())?"":e.toLocaleString("ko-KR",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return ""}}var De=class{hbs;execPolicy;execEnabled;constructor(e={}){this.hbs=ie__namespace.create(),this.execPolicy=e.execPolicy??{allow:[],deny:[]},this.execEnabled=e.execEnabled??true,this.registerHelpers();}registerHelpers(){let e=this.hbs,t=this.execPolicy,n=this.execEnabled;e.registerHelper("exec",function(o){return typeof o!="string"?"":n?new e.SafeString(Wr(o,t)):"(exec disabled)"}),e.registerHelper("include",function(o){return new e.SafeString(Jr(o))}),e.registerHelper("fenced_code",function(o,s){return new e.SafeString(Vr(o,s))}),e.registerHelper("eq",function(o,s){return o===s}),e.registerHelper("ne",function(o,s){return o!==s}),e.registerHelper("and",function(o,s){return o&&s}),e.registerHelper("or",function(o,s){return o||s}),e.registerHelper("not",function(o){return !o}),e.registerHelper("contains",function(o,s){return Array.isArray(o)&&o.includes(s)}),e.registerHelper("json",function(o){return JSON.stringify(o,null,2)}),e.registerHelper("truncate",function(o,s){return Dt(o,s)}),e.registerHelper("length",function(o){return Ht(o)}),e.registerHelper("escapeHandlebars",function(o){return new e.SafeString(Lt(o))}),e.registerHelper("formatFileSize",function(o){return qt(o)}),e.registerHelper("formatTimestamp",function(o){return Ft(o)});}async render(e,t={}){return this.hbs.compile(e,{noEscape:true})(t)}};y();y();var ht=class{async readFile(e){return promises.readFile(e,"utf-8")}async exists(e){try{return await promises.access(e),!0}catch{return false}}resolvePath(...e){return e.length===1?X.resolve(e[0]):X.resolve(X.join(...e))}isAbsolute(e){return X.isAbsolute(e)}},Ut=new ht;var Ce=class{docs=new Map;fs;constructor(e){this.fs=e??Ut;}async load(e,t){if(e)for(let[n,o]of Object.entries(e)){let s=o;if(typeof s=="string")this.docs.set(n,{content:s});else if(s&&typeof s=="object"){let i=s;"content"in i&&typeof i.content=="string"?this.docs.set(n,{content:i.content}):"path"in i&&typeof i.path=="string"?await this.loadFromFile(n,i.path,t):console.warn(`[DocumentLoader] Skipping '${n}': unsupported format`);}else console.warn(`[DocumentLoader] Skipping '${n}': unsupported format`);}}async getContent(e){return this.docs.get(e)?.content}async getToc(e){let t=this.docs.get(e);if(!t)return;let n=[];for(let o of t.content.split(`
46
+ \`\`\``}h();function Ft(r,e){if(!r)return "";if(r.length<=e)return r;let t=r.length-e;return `${r.substring(0,e)} (...+${t} chars)`}function Ut(r){return Array.isArray(r)||typeof r=="string"?r.length:0}function Bt(r){return typeof r!="string"?"":r.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}var en=["B","KB","MB","GB"];function Wt(r){if(r===0)return "0 B";let e=Math.min(Math.floor(Math.log(r)/Math.log(1024)),en.length-1);return `${Math.round(r/Math.pow(1024,e)*100)/100} ${en[e]}`}function Jt(r){if(!r)return "";try{let e=r instanceof Date?r:new Date(r);return isNaN(e.getTime())?"":e.toLocaleString("ko-KR",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return ""}}var $e=class{hbs;execPolicy;execEnabled;constructor(e={}){this.hbs=ie__namespace.create(),this.execPolicy=e.execPolicy??{allow:[],deny:[]},this.execEnabled=e.execEnabled??true,this.registerHelpers();}registerHelpers(){let e=this.hbs,t=this.execPolicy,n=this.execEnabled;e.registerHelper("exec",function(o){return typeof o!="string"?"":n?new e.SafeString(Yr(o,t)):"(exec disabled)"}),e.registerHelper("include",function(o){return new e.SafeString(Qr(o))}),e.registerHelper("fenced_code",function(o,s){return new e.SafeString(Zr(o,s))}),e.registerHelper("eq",function(o,s){return o===s}),e.registerHelper("ne",function(o,s){return o!==s}),e.registerHelper("and",function(o,s){return o&&s}),e.registerHelper("or",function(o,s){return o||s}),e.registerHelper("not",function(o){return !o}),e.registerHelper("contains",function(o,s){return Array.isArray(o)&&o.includes(s)}),e.registerHelper("json",function(o){return JSON.stringify(o,null,2)}),e.registerHelper("truncate",function(o,s){return Ft(o,s)}),e.registerHelper("length",function(o){return Ut(o)}),e.registerHelper("escapeHandlebars",function(o){return new e.SafeString(Bt(o))}),e.registerHelper("formatFileSize",function(o){return Wt(o)}),e.registerHelper("formatTimestamp",function(o){return Jt(o)});}async render(e,t={}){return this.hbs.compile(e,{noEscape:true})(t)}};h();h();var ht=class{async readFile(e){return promises.readFile(e,"utf-8")}async exists(e){try{return await promises.access(e),!0}catch{return false}}resolvePath(...e){return e.length===1?X.resolve(e[0]):X.resolve(X.join(...e))}isAbsolute(e){return X.isAbsolute(e)}},Vt=new ht;var Ce=class{docs=new Map;fs;constructor(e){this.fs=e??Vt;}async load(e,t){if(e)for(let[n,o]of Object.entries(e)){let s=o;if(typeof s=="string")this.docs.set(n,{content:s});else if(s&&typeof s=="object"){let i=s;"content"in i&&typeof i.content=="string"?this.docs.set(n,{content:i.content}):"path"in i&&typeof i.path=="string"?await this.loadFromFile(n,i.path,t):console.warn(`[DocumentLoader] Skipping '${n}': unsupported format`);}else console.warn(`[DocumentLoader] Skipping '${n}': unsupported format`);}}async getContent(e){return this.docs.get(e)?.content}async getToc(e){let t=this.docs.get(e);if(!t)return;let n=[];for(let o of t.content.split(`
47
47
  `)){let s=/^(#{1,6})\s+(.+)$/.exec(o.trim());s&&n.push({depth:s[1].length,text:s[2].trim()});}if(n.length!==0)return n.map(({depth:o,text:s})=>`${" ".repeat(o-1)}- ${s}`).join(`
48
- `)}getPath(e){return this.docs.get(e)?.path}getNames(){return Array.from(this.docs.keys())}async buildContext(){let e={};for(let t of this.docs.keys()){let n=await this.getContent(t)??"",o=await this.getToc(t),s=this.getPath(t);e[t]={content:n,toc:o,...s?{path:s}:{}};}return e}async loadFromFile(e,t,n){try{let o=this.resolve(t,n),s=await this.fs.readFile(o);this.docs.set(e,{content:s,path:o});}catch(o){let s=o instanceof Error?o.message:String(o);console.warn(`[DocumentLoader] Failed to load '${e}' from '${t}': ${s}`);}}resolve(e,t){return this.fs.isAbsolute(e)?e:t?this.fs.resolvePath(t,e):this.fs.resolvePath(e)}};y();y();var Q=class extends Error{constructor(t,n,o){super(t);this.layoutId=n;this.cause=o;this.name="LayoutLoadError";}layoutId;cause},ge=class extends Error{constructor(t,n=[],o){super(t);this.errors=n;this.cause=o;this.name="PropsValidationError";}errors;cause};var bi={validationMode:"lenient",fallbackLayoutId:"crewx/default"},He=class{layouts=new Map;options;constructor(e){this.options={...bi,...e,templatesPath:e?.templatesPath??Se()},this.loadAllLayouts();}load(e,t){let n=this.layouts.get(e);if(!n){let o=this.normalizeLayoutId(e);n=this.layouts.get(o);}if(!n&&(console.warn(`Layout not found: ${e}, falling back to ${this.options.fallbackLayoutId}`),n=this.layouts.get(this.options.fallbackLayoutId),!n))throw new Q(`Fallback layout not found: ${this.options.fallbackLayoutId}`,this.options.fallbackLayoutId);return t&&Object.keys(t).length>0?{...n,defaultProps:{...n.defaultProps,...t}}:n}getLayoutIds(){return Array.from(this.layouts.keys())}hasLayout(e){if(this.layouts.has(e))return true;let t=this.normalizeLayoutId(e);return this.layouts.has(t)}reload(){this.layouts.clear(),this.loadAllLayouts();}registerLayout(e,t){if(!e||typeof e!="string")throw new Q("Layout ID must be a non-empty string",e);let n=typeof t=="string"?{template:t}:t,o=typeof n.template=="string"?n.template:"";if(!o||o.trim().length===0)throw new Q(`Custom layout template is empty for ${e}`,e);let s=n.propsSchema||{},i=this.extractDefaultProps(s),a=n.defaultProps||{},l={id:e,version:n.version||"1.0.0",description:n.description||`Custom layout ${e}`,template:o,propsSchema:this.parsePropsSchema(s),defaultProps:{...i,...a}},u=this.layouts.get(e),c=u?.template===o&&JSON.stringify(u?.defaultProps??{})===JSON.stringify(l.defaultProps??{})&&JSON.stringify(u?.propsSchema??{})===JSON.stringify(l.propsSchema??{});this.layouts.set(e,l),process.env.CREWX_VERBOSE==="1"&&(u?c||console.error(`Updated custom layout: ${e}`):console.error(`Registered custom layout: ${e}`));}registerLayouts(e){for(let[t,n]of Object.entries(e))try{this.registerLayout(t,n);}catch(o){console.warn(`Failed to register custom layout ${t}:`,o instanceof Error?o.message:o);}}loadAllLayouts(){let e=this.options.templatesPath;if(!fs$1.existsSync(e))throw new Q(`Templates directory not found: ${e}`,void 0,new Error(`Directory does not exist: ${e}`));try{let t=fs$1.readdirSync(e).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));t.length===0&&console.warn(`No layout files found in ${e}`);for(let n of t){let o=n.replace(/\.(yaml|yml)$/,""),s=X__namespace.join(e,n);try{let i=this.loadLayoutFile(s,o),a=`crewx/${o}`;this.layouts.set(a,i),a!=="crewx/minimal"&&process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded layout: ${a} from ${n}`);}catch(i){console.error(`Failed to load layout file ${n}:`,i);}}process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded ${this.layouts.size} layouts from ${e}`);}catch(t){throw new Q(`Failed to read layouts directory: ${e}`,void 0,t instanceof Error?t:new Error(String(t)))}}loadLayoutFile(e,t){try{let n=fs$1.readFileSync(e,"utf-8");if(!n||n.trim().length===0)throw console.warn(`Empty YAML file: ${e}, will use fallback`),new Q(`Empty YAML file: ${e}`,t,new Error("File content is empty"));let o=jsYaml.load(n);if(!o||typeof o!="object")throw console.warn(`Invalid YAML content in ${e} (parsed as ${typeof o}), will use fallback`),new Q(`Invalid or empty YAML in ${e}`,t,new Error("YAML parsing returned null/undefined or non-object"));if(o.layouts&&typeof o.layouts=="object"){let s=this.resolveLayoutEntry(o.layouts,t);if(!s||s.template.trim().length===0)throw console.warn(`Empty or missing layout template in ${e} for ${t}`),new Q(`Layout template not found or empty in layouts map: ${t}`,t);let i=s.propsSchema||o.propsSchema||{};return {id:`crewx/${t}`,version:o.version||"1.0.0",description:o.description||`CrewX ${t} layout`,template:s.template,propsSchema:this.parsePropsSchema(i),defaultProps:this.extractDefaultProps(i)}}else {if(!o.template||typeof o.template=="string"&&o.template.trim().length===0)throw console.warn(`Empty or missing template field in ${e}`),new Q(`Layout template is missing or empty in ${e}`,t);return {id:o.id||`crewx/${t}`,version:o.version||"1.0.0",description:o.description||"",template:o.template,propsSchema:this.parsePropsSchema(o.propsSchema||{}),defaultProps:this.extractDefaultProps(o.propsSchema||{})}}}catch(n){throw new Q(`Failed to load layout file: ${e}`,t,n instanceof Error?n:new Error(String(n)))}}parsePropsSchema(e){let t={};for(let[n,o]of Object.entries(e))typeof o=="object"&&o!==null&&(t[n]=o);return t}extractDefaultProps(e){let t={};for(let[n,o]of Object.entries(e))o&&typeof o=="object"&&("defaultValue"in o?t[n]=o.defaultValue:"default"in o&&(t[n]=o.default));return t}normalizeLayoutId(e){return e?e.includes("/")?e:`crewx/${e}`:this.options.fallbackLayoutId}resolveLayoutEntry(e,t){let n=new Set;if(t)if(n.add(t),t.includes("/")){let o=t.split("/"),s=o[o.length-1];s&&n.add(s);}else n.add(`crewx/${t}`);n.add("default");for(let o of n){let s=e[o];if(typeof s=="string"&&s.trim().length>0)return {template:s};if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}for(let o of Object.values(e)){if(typeof o=="string"&&o.trim().length>0)return {template:o};let s=o;if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}}};y();y();function _i(r){return Array.from(new Set(r.filter(e=>e?.isAssistant&&e?.metadata?.agent_id).map(e=>String(e.metadata.agent_id))))}function Qr(r,e,t){if(!Array.isArray(r)||r.length===0||!(t&&typeof t.fn=="function"))return "";let o=_i(r),s=o.length>0?o[0]:"",i={messages:r,platform:typeof e=="string"?e:"",messagesCount:r.length,agentIds:o,primaryAgentId:s};return t.fn(i)}y();var Le=class{defaultMode;constructor(e={}){this.defaultMode=e.defaultMode??"lenient";}validate(e,t,n=this.defaultMode){let o=[],s=this.validateObject(e??{},t,n,["props"],o);if(o.length>0&&n==="strict")throw new ge("Props validation failed in strict mode",o);return {valid:o.length===0,props:s,errors:o}}validateObject(e,t,n,o,s){let i={};if(n==="strict")for(let a of Object.keys(e))t[a]||s.push({path:this.buildPath([...o,a]),message:`Unknown prop '${a}'`,value:e[a]});for(let[a,l]of Object.entries(t)){let u=[...o,a],c=e[a],p=this.resolveProp(c,l,u,n,s);p.shouldAssign&&(i[a]=p.value);}return i}resolveProp(e,t,n,o,s){let i=this.buildPath(n);if(this.isNil(e)){if(t.isRequired&&s.push({path:i,message:`Required prop '${n[n.length-1]}' is missing`}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let l=this.applyDefaults(t.shape);if(Object.keys(l).length>0)return {shouldAssign:true,value:l}}return {shouldAssign:false}}let a=this.validateType(e,t,n,o,s);if(!a.valid){if(t.type==="shape"&&a.value&&this.isPlainObject(a.value))return {shouldAssign:true,value:a.value};if(s.push({path:i,message:a.error??"Invalid value",value:e}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let l=this.applyDefaults(t.shape);if(Object.keys(l).length>0)return {shouldAssign:true,value:l}}return {shouldAssign:false}}return {shouldAssign:true,value:a.value}}validateType(e,t,n,o,s){let{type:i}=t;switch(i){case "string":return this.validateString(e,t);case "number":return this.validateNumber(e,t);case "bool":return this.validateBoolean(e);case "array":return this.validateArray(e,t);case "arrayOf":return this.validateArrayOf(e,t,n,o,s);case "object":return this.validatePlainObject(e);case "shape":return this.validateShape(e,t,n,o,s);case "oneOfType":return this.validateOneOfType(e,t);case "func":return this.validateFunction(e);case "node":return {valid:true,value:e};default:return {valid:true,value:e}}}validateString(e,t){return typeof e!="string"?{valid:false,error:`Expected string, got ${this.describeType(e)}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`String length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`String length must be <= ${t.maxLength}`}:t.pattern&&!new RegExp(t.pattern).test(e)?{valid:false,error:`String does not match pattern ${t.pattern}`}:{valid:true,value:e}}validateNumber(e,t){return typeof e!="number"||Number.isNaN(e)?{valid:false,error:`Expected number, got ${this.describeType(e)}`}:t.min!==void 0&&e<t.min?{valid:false,error:`Number must be >= ${t.min}`}:t.max!==void 0&&e>t.max?{valid:false,error:`Number must be <= ${t.max}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:{valid:true,value:e}}validateBoolean(e){return typeof e!="boolean"?{valid:false,error:`Expected boolean, got ${this.describeType(e)}`}:{valid:true,value:e}}validateArray(e,t){return Array.isArray(e)?t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`Array length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`Array length must be <= ${t.maxLength}`}:{valid:true,value:[...e]}:{valid:false,error:`Expected array, got ${this.describeType(e)}`}}validateArrayOf(e,t,n,o,s){let i=this.validateArray(e,t);if(!i.valid)return i;let a=[],l=t.itemType,u=t.itemOneOf,c=s.length;return i.value.forEach((p,g)=>{let m=[...n,String(g)];if(l){let v=this.validateType(p,{type:l},m,o,s);v.valid?a.push(v.value):s.push({path:this.buildPath(m),message:v.error??"Invalid array item",value:p});}else a.push(p);u&&!u.includes(p)&&s.push({path:this.buildPath(m),message:`Array item must be one of: ${u.join(", ")}`,value:p});}),{valid:s.length===c,value:a}}validatePlainObject(e){return this.isPlainObject(e)?{valid:true,value:{...e}}:{valid:false,error:`Expected object, got ${this.describeType(e)}`}}validateFunction(e){return typeof e!="function"?{valid:false,error:`Expected function, got ${this.describeType(e)}`}:{valid:true,value:e}}validateShape(e,t,n,o,s){if(!this.isPlainObject(e))return {valid:false,error:`Expected object, got ${this.describeType(e)}`};let i=s.length,a=this.validateObject(e,t.shape??{},o,n,s);return {valid:s.length===i,value:a}}validateOneOfType(e,t){let n=t.types??[];return n.some(s=>this.matchesType(e,s))?{valid:true,value:e}:{valid:false,error:`Value does not match any allowed type: ${n.join(", ")}`}}matchesType(e,t){switch(t){case "string":return typeof e=="string";case "number":return typeof e=="number"&&!Number.isNaN(e);case "bool":case "boolean":return typeof e=="boolean";case "array":return Array.isArray(e);case "object":return this.isPlainObject(e);case "func":case "function":return typeof e=="function";case "shape":return this.isPlainObject(e);case "node":return e==null||typeof e!="symbol";default:return true}}applyDefaults(e){let t={};for(let[n,o]of Object.entries(e)){if(o.defaultValue!==void 0){t[n]=this.cloneValue(o.defaultValue);continue}if(o.type==="shape"&&o.shape){let s=this.applyDefaults(o.shape);Object.keys(s).length>0&&(t[n]=s);}}return t}cloneValue(e){if(Array.isArray(e))return e.map(t=>this.cloneValue(t));if(this.isPlainObject(e)){let t={};for(let[n,o]of Object.entries(e))t[n]=this.cloneValue(o);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}isNil(e){return e==null}buildPath(e){return e.join(".")}describeType(e){return Array.isArray(e)?"array":e===null?"null":typeof e}};var qe=class{handlebars;propsValidator;constructor(e){this.handlebars=ie__namespace.default.create(),this.propsValidator=e??new Le,this.registerHelpers();}render(e,t,n={}){try{let o=this.prepareRenderContext(e,t,n);return this.handlebars.compile(e.template,{noEscape:!0})(o)}catch(o){throw o instanceof Error?new Error(`Template rendering failed for layout '${e.id}': ${o.message}`):new Error(`Unknown error rendering layout '${e.id}'`)}}validate(e,t,n="lenient"){return this.executeValidation(e,t,n)}resolveProps(e,t,n="lenient"){let o=this.mergeProps(e.defaultProps,t);return !e.propsSchema||Object.keys(e.propsSchema).length===0?{valid:true,props:o,errors:[]}:this.executeValidation(o,e.propsSchema,n)}prepareRenderContext(e,t,n){let{validationMode:o="lenient",skipValidation:s=false}=n,i=s?this.mergeProps(e.defaultProps,t.props):this.resolveProps(e,t.props,o).props;return {...t,vars:this.sanitizeVars(t.vars),props:i}}registerHelpers(){this.handlebars.registerHelper("formatConversation",Qr),ie__namespace.default.helpers.each&&this.handlebars.registerHelper("each",ie__namespace.default.helpers.each),ie__namespace.default.helpers.if&&this.handlebars.registerHelper("if",ie__namespace.default.helpers.if),ie__namespace.default.helpers.unless&&this.handlebars.registerHelper("unless",ie__namespace.default.helpers.unless),ie__namespace.default.helpers.with&&this.handlebars.registerHelper("with",ie__namespace.default.helpers.with),this.handlebars.registerHelper("eq",function(e,t){return e===t}),this.handlebars.registerHelper("ne",function(e,t){return e!==t}),this.handlebars.registerHelper("gt",function(e,t){return e>t}),this.handlebars.registerHelper("lt",function(e,t){return e<t}),this.handlebars.registerHelper("json",function(e){return new ie__namespace.default.SafeString(JSON.stringify(e))}),this.handlebars.registerHelper("raw",function(e){return typeof e?.fn=="function"?e.fn(this):""}),this.handlebars.registerHelper("escapeHandlebars",function(e){return typeof e!="string"?"":e.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}),this.handlebars.registerHelper("formatFileSize",function(e){if(e===0)return "0 B";let t=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]});}executeValidation(e,t,n){try{return this.propsValidator.validate(e,t,n)}catch(o){if(o instanceof ge&&o.errors&&o.errors.length>0){let s=o.errors[0];if(s)throw new ge(s.message,o.errors)}throw o}}mergeProps(e,t){let n=this.cloneDeep(e??{});return t?this.deepMerge(n,t):n}deepMerge(e,t){for(let[n,o]of Object.entries(t)){if(this.isPlainObject(o)){let s=e[n];e[n]=this.deepMerge(this.isPlainObject(s)?s:{},o);continue}if(Array.isArray(o)){e[n]=this.cloneDeep(o);continue}e[n]=o;}return e}cloneDeep(e){if(Array.isArray(e))return e.map(t=>this.cloneDeep(t));if(this.isPlainObject(e)){let t={};for(let[n,o]of Object.entries(e))t[n]=this.cloneDeep(o);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}sanitizeVars(e){if(!e)return {};let t={...e};if(typeof e.user_input=="string"){t.user_input_raw=e.user_input;let n=e.user_input.replace(/\{\{\{/g,"&#123;&#123;&#123;").replace(/\}\}\}/g,"&#125;&#125;&#125;").replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;");t.user_input=this.handlebars.escapeExpression(n);}return t}};y();var Bt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xi(r){let e=crypto$1.randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=Bt[o%62]);}for(;t.length<r;)t+=Bt[crypto$1.randomBytes(1)[0]%62];return t}function Te(r){return `${r}_${xi(8)}`}function ki(r,e){let{createHash:t}=U("crypto"),n=t("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=n[i];let s="";for(let i of o)s+=Bt[i%62];return `${r}_${s}`}y();function Wt(r){let e=t=>String(t).padStart(2,"0");return `${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}T${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}y();function en(r,e){return t=>{try{let n=e(t);n instanceof Promise&&n.catch(o=>{console.error(`[crewx] event listener error (${r}): ${o instanceof Error?o.message:String(o)}`);});}catch(n){console.error(`[crewx] event listener error (${r}): ${n instanceof Error?n.message:String(n)}`);}}}var Fe=class{_emitter=new events.EventEmitter;on(e,t){let n=en(e,t);return this._emitter.on(e,n),()=>this._emitter.off(e,n)}once(e,t){let n=en(e,t);return this._emitter.once(e,n),()=>this._emitter.off(e,n)}emit(e,t){this._emitter.emit(e,t);}};y();function Jt(r){let e=new Map,t=n=>n.startsWith(`${r}::`)?n:`${r}::${n}`;return {async get(n){let o=e.get(t(n));return o?o.value:void 0},async set(n,o){e.set(t(n),{value:o});},async delete(n){return e.delete(t(n))},async list(n){let o=n?t(n):`${r}::`,s=[];for(let i of e.keys())i.startsWith(o)&&s.push(i.slice(r.length+2));return s}}}y();var Vt=new async_hooks.AsyncLocalStorage;function Ti(){return Vt}function Pi(r,e){return Vt.run(r,e)}function Kt(r){let e=r.log??r.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},t=r.agentRunner??{run:async()=>({output:""})},n=r.db??{get:async()=>{},set:async()=>{},delete:async()=>false,list:async()=>[]},o=r.storage??{put:async()=>"",get:async()=>{},delete:async()=>false},s=r.audit??{log:async()=>{}},i=r.onInbound??(async()=>({accepted:true})),a=r.onEmitEvent??(async()=>({accepted:true})),l=r.onUpdateMessage??(async()=>{}),u=r.onResolveUser??(async g=>({userId:g,displayName:g})),c=async g=>{let m=Vt.getStore();if(!m){e.warn("respondSync called outside sync window \u2014 graceful degradation (no-op)",{textPreview:typeof g=="object"&&"text"in g?g.text.slice(0,80):void 0});return}let v="text"in g?g.text:"";m.res.status(200).json({text:v});},p=r.httpRouter??{registerRoute:()=>{e.warn("httpRouter not configured \u2014 registerRoute is a no-op");}};return {instanceId:r.instanceId,config:r.config,capabilities:r.capabilities,log:e,agentRunner:t,db:n,storage:o,audit:s,abortSignal:r.abortSignal??new AbortController().signal,httpRouter:p,inbound:i,emitEvent:a,updateMessage:l,resolveUser:u,respondSync:c}}y();y();y();function ae(r){return /crewx\s+(x|execute)\s/.test(r)}function le(r,e){let t=e.match(/@(\S+)/);return {timestamp:r,type:"agent_call",targetAgent:t?.[1]?.replace(/["']/g,""),toolInput:e}}function tn(r,e){let n=e.message?.content;if(!Array.isArray(n))return [];let o=[];for(let s of n){let i=Ei(r,s);i&&o.push(i);}return o}function Ei(r,e){let t=e.type;if(t==="text"){let n=String(e.text||"");return n?{timestamp:r,type:"text",content:n}:null}if(t==="tool_use"){let n=String(e.name||""),o=e.id,s=e.input,i=s?.command?String(s.command):JSON.stringify(s||{});return n==="Bash"&&ae(i)?le(r,i):{timestamp:r,type:"tool_use",toolUseId:o,toolName:n,toolInput:i}}if(t==="tool_result"){let n=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
49
- `):i=JSON.stringify(s),{timestamp:r,type:"tool_result",toolUseId:o,resultPreview:i,isError:n}}return null}y();function rn(r,e){let t=e.type,n=e.data;if(!n)return [];let o=n.toolCallId;if(t==="tool.execution_start"){let s=String(n.toolName||""),i=n.arguments,a=i?.command?String(i.command):JSON.stringify(i||{});return (s==="bash"||s==="Bash")&&ae(a)?[le(r,a)]:[{timestamp:r,type:"tool_use",toolName:s,toolInput:a,...o&&{toolUseId:o}}]}if(t==="tool.execution_complete"){let s=n.error;if(s)return [{timestamp:r,type:"tool_result",isError:true,resultPreview:String(s.message||""),...o&&{toolUseId:o}}];let i=n.result,a=String(i?.content||"");return [{timestamp:r,type:"tool_result",resultPreview:a,isError:false,...o&&{toolUseId:o}}]}if(t==="assistant.message"){let s=String(n.content||"");return s?[{timestamp:r,type:"text",content:s}]:[]}return []}y();function nn(r,e){let t=e.type,n=e.item;if(!n)return [];if(t==="item.started")return Ai(r,n);if(t==="item.completed"){let o=Si(r,n);return o?[o]:[]}return []}function Ai(r,e){if(e.type==="command_execution"){let n=String(e.command||"");return ae(n)?[le(r,n)]:[{timestamp:r,type:"tool_use",toolName:"Bash",toolInput:n}]}return []}function Si(r,e){let t=e.type;if(t==="message"||t==="text"){let n=e.content;if(Array.isArray(n))for(let o of n){let s=Ii(r,o);if(s)return s}if(typeof e.text=="string")return {timestamp:r,type:"text",content:e.text}}if(t==="reasoning")return {timestamp:r,type:"text",content:String(e.text||"")};if(t==="command_execution"){let n=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:r,type:"tool_result",resultPreview:n,isError:o}}if(t==="tool_use"){let n=String(e.name||e.tool_name||""),o=e.input,s=o?.command?String(o.command):JSON.stringify(o||{});return n==="Bash"&&ae(s)?le(r,s):{timestamp:r,type:"tool_use",toolName:n,toolInput:s}}if(t==="tool_result"){let n=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:r,type:"tool_result",resultPreview:o,isError:n}}return null}function Ii(r,e){let t=e.type;if(t==="text")return {timestamp:r,type:"text",content:String(e.text||"")};if(t==="tool_use"){let n=String(e.name||""),o=e.input,s=o?.command?String(o.command):JSON.stringify(o||{});return n==="Bash"&&ae(s)?le(r,s):{timestamp:r,type:"tool_use",toolName:n,toolInput:s}}return null}y();function Gt(r,e){let t=e.type;if(t==="message"){if(e.role!=="assistant")return [];let o=e.content;return o?[{timestamp:r,type:"text",content:o}]:[]}if(t==="tool_use"){let n=String(e.tool_name||""),o=e.tool_id,s=e.parameters,i=s?.command?String(s.command):JSON.stringify(s||{});return /^bash$/i.test(n)&&ae(i)?[le(r,i)]:[{timestamp:r,type:"tool_use",toolName:n,toolUseId:o,toolInput:i}]}if(t==="tool_result"){let n=e.tool_id,o=String(e.output||""),s=e.status!=="success";return [{timestamp:r,type:"tool_result",toolUseId:n,resultPreview:o,isError:s}]}return []}y();function Xt(r,e){let t=e.type;if(t==="text"){let o=e.part?.text;return o?[{timestamp:r,type:"text",content:o}]:[]}if(t==="tool_use"){let n=e.part;if(!n)return [];let o=String(n.tool||""),s=String(n.callID||""),i=n.state,a=String(i?.status||""),l=i?.input,u=Oi(l),c=[{timestamp:r,type:"tool_use",toolName:o,toolUseId:s,toolInput:u}];if(a==="completed"&&i?.output!==void 0){let p=i.output,g=typeof p=="string"?p:JSON.stringify(p);c.push({timestamp:r,type:"tool_result",toolUseId:s,resultPreview:g,isError:false});}else a==="error"&&c.push({timestamp:r,type:"tool_result",toolUseId:s,resultPreview:String(i?.error||"tool error"),isError:true});return c}return []}function Oi(r){if(typeof r=="string")return r;if(!r||typeof r!="object")return JSON.stringify(r??{});let e=r;return e.command?String(e.command):e.filePath?String(e.filePath):e.pattern?String(e.pattern):JSON.stringify(e)}function Yt(r,e){let t;try{t=JSON.parse(e);}catch{return []}let n=t.type;return n?n==="assistant"||n==="user"?tn(r,t):n.startsWith("tool.execution")||n.startsWith("assistant.")||n==="user.message"?rn(r,t):n.startsWith("item.")||n.startsWith("turn.")||n.startsWith("thread.")?nn(r,t):n==="message"||n==="init"?Gt(r,t):n==="tool_use"||n==="tool_result"?t.part&&typeof t.part=="object"?Xt(r,t):Gt(r,t):n==="text"||n==="step_start"||n==="step_finish"?Xt(r,t):[]:[]}y();function zi(r){return typeof r!="string"?"":r.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qt(r){return r.messages.map(e=>({text:zi(e.text),isAssistant:e.isAssistant,metadata:e.metadata,files:void 0}))}y();y();var Mi={agentId:zod.z.string().describe("The agent ID to query"),query:zod.z.string().describe("The query message to send"),context:zod.z.string().optional().describe("Additional context"),thread:zod.z.string().optional().describe("Thread ID for conversation continuity")},ji={agentId:zod.z.string().describe("The agent ID to execute"),task:zod.z.string().describe("The task description to execute"),context:zod.z.string().optional().describe("Additional context"),thread:zod.z.string().optional().describe("Thread ID for conversation continuity")};function on(r,e,t){r.tool("crewx_listAgents","List available CrewX agents exposed by this server",async()=>{let n=[];for(let o of t){let s=e.agents.get(o);s&&n.push({id:s.id,name:s.name??s.id,description:s.description??""});}return {content:[{type:"text",text:JSON.stringify(n,null,2)}]}}),r.tool("crewx_queryAgent","Query a CrewX agent with a read-only question",Mi,async({agentId:n,query:o,context:s,thread:i})=>{if(!t.has(n))return {content:[{type:"text",text:`Agent '${n}' is not exposed by this server`}],isError:true};let a=await e.query(n,o,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Query failed"}],isError:true}}),r.tool("crewx_executeAgent","Execute a task on a CrewX agent (may modify state)",ji,async({agentId:n,task:o,context:s,thread:i})=>{if(!t.has(n))return {content:[{type:"text",text:`Agent '${n}' is not exposed by this server`}],isError:true};let a=await e.execute(n,o,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Execute failed"}],isError:true}});}y();function sn(r){return r.headers.get("Origin")?null:new Response(JSON.stringify({error:"Forbidden: Origin header required"}),{status:403,headers:{"Content-Type":"application/json"}})}async function an(r,e){return e?await e(r)?null:new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:{"Content-Type":"application/json"}}):null}function Di(r,e){let t=new mcp_js.McpServer({name:"crewx-mcp-server",version:"1.0.0"},{capabilities:{tools:{}}});return on(t,r,e),t}function Zt(r,e){if(!e.agents||e.agents.length===0)throw new Error("crewx.handler() requires at least one agent in the agents option");let t=new Set(e.agents),n=new Map;return async o=>{let s=sn(o);if(s)return s;let i=await an(o,e.auth);if(i)return i;let a=o.headers.get("mcp-session-id");if(a&&n.has(a))return n.get(a).transport.handleRequest(o);let l=Di(r,t),u=new webStandardStreamableHttp_js.WebStandardStreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID(),onsessioninitialized:c=>{n.set(c,{transport:u,server:l});},onsessionclosed:c=>{n.delete(c);},enableJsonResponse:true});return await l.connect(u),u.handleRequest(o)}}y();y();var Ue=class{detach(e){}};y();var Fi=`
48
+ `)}getPath(e){return this.docs.get(e)?.path}getNames(){return Array.from(this.docs.keys())}async buildContext(){let e={};for(let t of this.docs.keys()){let n=await this.getContent(t)??"",o=await this.getToc(t),s=this.getPath(t);e[t]={content:n,toc:o,...s?{path:s}:{}};}return e}async loadFromFile(e,t,n){try{let o=this.resolve(t,n),s=await this.fs.readFile(o);this.docs.set(e,{content:s,path:o});}catch(o){let s=o instanceof Error?o.message:String(o);console.warn(`[DocumentLoader] Failed to load '${e}' from '${t}': ${s}`);}}resolve(e,t){return this.fs.isAbsolute(e)?e:t?this.fs.resolvePath(t,e):this.fs.resolvePath(e)}};h();h();var Q=class extends Error{constructor(t,n,o){super(t);this.layoutId=n;this.cause=o;this.name="LayoutLoadError";}layoutId;cause},ge=class extends Error{constructor(t,n=[],o){super(t);this.errors=n;this.cause=o;this.name="PropsValidationError";}errors;cause};var Pi={validationMode:"lenient",fallbackLayoutId:"crewx/default"},He=class{layouts=new Map;options;constructor(e){this.options={...Pi,...e,templatesPath:e?.templatesPath??Se()},this.loadAllLayouts();}load(e,t){let n=this.layouts.get(e);if(!n){let o=this.normalizeLayoutId(e);n=this.layouts.get(o);}if(!n&&(console.warn(`Layout not found: ${e}, falling back to ${this.options.fallbackLayoutId}`),n=this.layouts.get(this.options.fallbackLayoutId),!n))throw new Q(`Fallback layout not found: ${this.options.fallbackLayoutId}`,this.options.fallbackLayoutId);return t&&Object.keys(t).length>0?{...n,defaultProps:{...n.defaultProps,...t}}:n}getLayoutIds(){return Array.from(this.layouts.keys())}hasLayout(e){if(this.layouts.has(e))return true;let t=this.normalizeLayoutId(e);return this.layouts.has(t)}reload(){this.layouts.clear(),this.loadAllLayouts();}registerLayout(e,t){if(!e||typeof e!="string")throw new Q("Layout ID must be a non-empty string",e);let n=typeof t=="string"?{template:t}:t,o=typeof n.template=="string"?n.template:"";if(!o||o.trim().length===0)throw new Q(`Custom layout template is empty for ${e}`,e);let s=n.propsSchema||{},i=this.extractDefaultProps(s),a=n.defaultProps||{},l={id:e,version:n.version||"1.0.0",description:n.description||`Custom layout ${e}`,template:o,propsSchema:this.parsePropsSchema(s),defaultProps:{...i,...a}},u=this.layouts.get(e),c=u?.template===o&&JSON.stringify(u?.defaultProps??{})===JSON.stringify(l.defaultProps??{})&&JSON.stringify(u?.propsSchema??{})===JSON.stringify(l.propsSchema??{});this.layouts.set(e,l),process.env.CREWX_VERBOSE==="1"&&(u?c||console.error(`Updated custom layout: ${e}`):console.error(`Registered custom layout: ${e}`));}registerLayouts(e){for(let[t,n]of Object.entries(e))try{this.registerLayout(t,n);}catch(o){console.warn(`Failed to register custom layout ${t}:`,o instanceof Error?o.message:o);}}loadAllLayouts(){let e=this.options.templatesPath;if(!fs$1.existsSync(e))throw new Q(`Templates directory not found: ${e}`,void 0,new Error(`Directory does not exist: ${e}`));try{let t=fs$1.readdirSync(e).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));t.length===0&&console.warn(`No layout files found in ${e}`);for(let n of t){let o=n.replace(/\.(yaml|yml)$/,""),s=X__namespace.join(e,n);try{let i=this.loadLayoutFile(s,o),a=`crewx/${o}`;this.layouts.set(a,i),a!=="crewx/minimal"&&process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded layout: ${a} from ${n}`);}catch(i){console.error(`Failed to load layout file ${n}:`,i);}}process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded ${this.layouts.size} layouts from ${e}`);}catch(t){throw new Q(`Failed to read layouts directory: ${e}`,void 0,t instanceof Error?t:new Error(String(t)))}}loadLayoutFile(e,t){try{let n=fs$1.readFileSync(e,"utf-8");if(!n||n.trim().length===0)throw console.warn(`Empty YAML file: ${e}, will use fallback`),new Q(`Empty YAML file: ${e}`,t,new Error("File content is empty"));let o=jsYaml.load(n);if(!o||typeof o!="object")throw console.warn(`Invalid YAML content in ${e} (parsed as ${typeof o}), will use fallback`),new Q(`Invalid or empty YAML in ${e}`,t,new Error("YAML parsing returned null/undefined or non-object"));if(o.layouts&&typeof o.layouts=="object"){let s=this.resolveLayoutEntry(o.layouts,t);if(!s||s.template.trim().length===0)throw console.warn(`Empty or missing layout template in ${e} for ${t}`),new Q(`Layout template not found or empty in layouts map: ${t}`,t);let i=s.propsSchema||o.propsSchema||{};return {id:`crewx/${t}`,version:o.version||"1.0.0",description:o.description||`CrewX ${t} layout`,template:s.template,propsSchema:this.parsePropsSchema(i),defaultProps:this.extractDefaultProps(i)}}else {if(!o.template||typeof o.template=="string"&&o.template.trim().length===0)throw console.warn(`Empty or missing template field in ${e}`),new Q(`Layout template is missing or empty in ${e}`,t);return {id:o.id||`crewx/${t}`,version:o.version||"1.0.0",description:o.description||"",template:o.template,propsSchema:this.parsePropsSchema(o.propsSchema||{}),defaultProps:this.extractDefaultProps(o.propsSchema||{})}}}catch(n){throw new Q(`Failed to load layout file: ${e}`,t,n instanceof Error?n:new Error(String(n)))}}parsePropsSchema(e){let t={};for(let[n,o]of Object.entries(e))typeof o=="object"&&o!==null&&(t[n]=o);return t}extractDefaultProps(e){let t={};for(let[n,o]of Object.entries(e))o&&typeof o=="object"&&("defaultValue"in o?t[n]=o.defaultValue:"default"in o&&(t[n]=o.default));return t}normalizeLayoutId(e){return e?e.includes("/")?e:`crewx/${e}`:this.options.fallbackLayoutId}resolveLayoutEntry(e,t){let n=new Set;if(t)if(n.add(t),t.includes("/")){let o=t.split("/"),s=o[o.length-1];s&&n.add(s);}else n.add(`crewx/${t}`);n.add("default");for(let o of n){let s=e[o];if(typeof s=="string"&&s.trim().length>0)return {template:s};if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}for(let o of Object.values(e)){if(typeof o=="string"&&o.trim().length>0)return {template:o};let s=o;if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}}};h();h();function Ei(r){return Array.from(new Set(r.filter(e=>e?.isAssistant&&e?.metadata?.agent_id).map(e=>String(e.metadata.agent_id))))}function on(r,e,t){if(!Array.isArray(r)||r.length===0||!(t&&typeof t.fn=="function"))return "";let o=Ei(r),s=o.length>0?o[0]:"",i={messages:r,platform:typeof e=="string"?e:"",messagesCount:r.length,agentIds:o,primaryAgentId:s};return t.fn(i)}h();var Le=class{defaultMode;constructor(e={}){this.defaultMode=e.defaultMode??"lenient";}validate(e,t,n=this.defaultMode){let o=[],s=this.validateObject(e??{},t,n,["props"],o);if(o.length>0&&n==="strict")throw new ge("Props validation failed in strict mode",o);return {valid:o.length===0,props:s,errors:o}}validateObject(e,t,n,o,s){let i={};if(n==="strict")for(let a of Object.keys(e))t[a]||s.push({path:this.buildPath([...o,a]),message:`Unknown prop '${a}'`,value:e[a]});for(let[a,l]of Object.entries(t)){let u=[...o,a],c=e[a],m=this.resolveProp(c,l,u,n,s);m.shouldAssign&&(i[a]=m.value);}return i}resolveProp(e,t,n,o,s){let i=this.buildPath(n);if(this.isNil(e)){if(t.isRequired&&s.push({path:i,message:`Required prop '${n[n.length-1]}' is missing`}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let l=this.applyDefaults(t.shape);if(Object.keys(l).length>0)return {shouldAssign:true,value:l}}return {shouldAssign:false}}let a=this.validateType(e,t,n,o,s);if(!a.valid){if(t.type==="shape"&&a.value&&this.isPlainObject(a.value))return {shouldAssign:true,value:a.value};if(s.push({path:i,message:a.error??"Invalid value",value:e}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let l=this.applyDefaults(t.shape);if(Object.keys(l).length>0)return {shouldAssign:true,value:l}}return {shouldAssign:false}}return {shouldAssign:true,value:a.value}}validateType(e,t,n,o,s){let{type:i}=t;switch(i){case "string":return this.validateString(e,t);case "number":return this.validateNumber(e,t);case "bool":return this.validateBoolean(e);case "array":return this.validateArray(e,t);case "arrayOf":return this.validateArrayOf(e,t,n,o,s);case "object":return this.validatePlainObject(e);case "shape":return this.validateShape(e,t,n,o,s);case "oneOfType":return this.validateOneOfType(e,t);case "func":return this.validateFunction(e);case "node":return {valid:true,value:e};default:return {valid:true,value:e}}}validateString(e,t){return typeof e!="string"?{valid:false,error:`Expected string, got ${this.describeType(e)}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`String length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`String length must be <= ${t.maxLength}`}:t.pattern&&!new RegExp(t.pattern).test(e)?{valid:false,error:`String does not match pattern ${t.pattern}`}:{valid:true,value:e}}validateNumber(e,t){return typeof e!="number"||Number.isNaN(e)?{valid:false,error:`Expected number, got ${this.describeType(e)}`}:t.min!==void 0&&e<t.min?{valid:false,error:`Number must be >= ${t.min}`}:t.max!==void 0&&e>t.max?{valid:false,error:`Number must be <= ${t.max}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:{valid:true,value:e}}validateBoolean(e){return typeof e!="boolean"?{valid:false,error:`Expected boolean, got ${this.describeType(e)}`}:{valid:true,value:e}}validateArray(e,t){return Array.isArray(e)?t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`Array length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`Array length must be <= ${t.maxLength}`}:{valid:true,value:[...e]}:{valid:false,error:`Expected array, got ${this.describeType(e)}`}}validateArrayOf(e,t,n,o,s){let i=this.validateArray(e,t);if(!i.valid)return i;let a=[],l=t.itemType,u=t.itemOneOf,c=s.length;return i.value.forEach((m,p)=>{let g=[...n,String(p)];if(l){let v=this.validateType(m,{type:l},g,o,s);v.valid?a.push(v.value):s.push({path:this.buildPath(g),message:v.error??"Invalid array item",value:m});}else a.push(m);u&&!u.includes(m)&&s.push({path:this.buildPath(g),message:`Array item must be one of: ${u.join(", ")}`,value:m});}),{valid:s.length===c,value:a}}validatePlainObject(e){return this.isPlainObject(e)?{valid:true,value:{...e}}:{valid:false,error:`Expected object, got ${this.describeType(e)}`}}validateFunction(e){return typeof e!="function"?{valid:false,error:`Expected function, got ${this.describeType(e)}`}:{valid:true,value:e}}validateShape(e,t,n,o,s){if(!this.isPlainObject(e))return {valid:false,error:`Expected object, got ${this.describeType(e)}`};let i=s.length,a=this.validateObject(e,t.shape??{},o,n,s);return {valid:s.length===i,value:a}}validateOneOfType(e,t){let n=t.types??[];return n.some(s=>this.matchesType(e,s))?{valid:true,value:e}:{valid:false,error:`Value does not match any allowed type: ${n.join(", ")}`}}matchesType(e,t){switch(t){case "string":return typeof e=="string";case "number":return typeof e=="number"&&!Number.isNaN(e);case "bool":case "boolean":return typeof e=="boolean";case "array":return Array.isArray(e);case "object":return this.isPlainObject(e);case "func":case "function":return typeof e=="function";case "shape":return this.isPlainObject(e);case "node":return e==null||typeof e!="symbol";default:return true}}applyDefaults(e){let t={};for(let[n,o]of Object.entries(e)){if(o.defaultValue!==void 0){t[n]=this.cloneValue(o.defaultValue);continue}if(o.type==="shape"&&o.shape){let s=this.applyDefaults(o.shape);Object.keys(s).length>0&&(t[n]=s);}}return t}cloneValue(e){if(Array.isArray(e))return e.map(t=>this.cloneValue(t));if(this.isPlainObject(e)){let t={};for(let[n,o]of Object.entries(e))t[n]=this.cloneValue(o);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}isNil(e){return e==null}buildPath(e){return e.join(".")}describeType(e){return Array.isArray(e)?"array":e===null?"null":typeof e}};var qe=class{handlebars;propsValidator;constructor(e){this.handlebars=ie__namespace.default.create(),this.propsValidator=e??new Le,this.registerHelpers();}render(e,t,n={}){try{let o=this.prepareRenderContext(e,t,n);return this.handlebars.compile(e.template,{noEscape:!0})(o)}catch(o){throw o instanceof Error?new Error(`Template rendering failed for layout '${e.id}': ${o.message}`):new Error(`Unknown error rendering layout '${e.id}'`)}}validate(e,t,n="lenient"){return this.executeValidation(e,t,n)}resolveProps(e,t,n="lenient"){let o=this.mergeProps(e.defaultProps,t);return !e.propsSchema||Object.keys(e.propsSchema).length===0?{valid:true,props:o,errors:[]}:this.executeValidation(o,e.propsSchema,n)}prepareRenderContext(e,t,n){let{validationMode:o="lenient",skipValidation:s=false}=n,i=s?this.mergeProps(e.defaultProps,t.props):this.resolveProps(e,t.props,o).props;return {...t,vars:this.sanitizeVars(t.vars),props:i}}registerHelpers(){this.handlebars.registerHelper("formatConversation",on),ie__namespace.default.helpers.each&&this.handlebars.registerHelper("each",ie__namespace.default.helpers.each),ie__namespace.default.helpers.if&&this.handlebars.registerHelper("if",ie__namespace.default.helpers.if),ie__namespace.default.helpers.unless&&this.handlebars.registerHelper("unless",ie__namespace.default.helpers.unless),ie__namespace.default.helpers.with&&this.handlebars.registerHelper("with",ie__namespace.default.helpers.with),this.handlebars.registerHelper("eq",function(e,t){return e===t}),this.handlebars.registerHelper("ne",function(e,t){return e!==t}),this.handlebars.registerHelper("gt",function(e,t){return e>t}),this.handlebars.registerHelper("lt",function(e,t){return e<t}),this.handlebars.registerHelper("json",function(e){return new ie__namespace.default.SafeString(JSON.stringify(e))}),this.handlebars.registerHelper("raw",function(e){return typeof e?.fn=="function"?e.fn(this):""}),this.handlebars.registerHelper("escapeHandlebars",function(e){return typeof e!="string"?"":e.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}),this.handlebars.registerHelper("formatFileSize",function(e){if(e===0)return "0 B";let t=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]});}executeValidation(e,t,n){try{return this.propsValidator.validate(e,t,n)}catch(o){if(o instanceof ge&&o.errors&&o.errors.length>0){let s=o.errors[0];if(s)throw new ge(s.message,o.errors)}throw o}}mergeProps(e,t){let n=this.cloneDeep(e??{});return t?this.deepMerge(n,t):n}deepMerge(e,t){for(let[n,o]of Object.entries(t)){if(this.isPlainObject(o)){let s=e[n];e[n]=this.deepMerge(this.isPlainObject(s)?s:{},o);continue}if(Array.isArray(o)){e[n]=this.cloneDeep(o);continue}e[n]=o;}return e}cloneDeep(e){if(Array.isArray(e))return e.map(t=>this.cloneDeep(t));if(this.isPlainObject(e)){let t={};for(let[n,o]of Object.entries(e))t[n]=this.cloneDeep(o);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}sanitizeVars(e){if(!e)return {};let t={...e};if(typeof e.user_input=="string"){t.user_input_raw=e.user_input;let n=e.user_input.replace(/\{\{\{/g,"&#123;&#123;&#123;").replace(/\}\}\}/g,"&#125;&#125;&#125;").replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;");t.user_input=this.handlebars.escapeExpression(n);}return t}};h();var Gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ai(r){let e=crypto$1.randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=Gt[o%62]);}for(;t.length<r;)t+=Gt[crypto$1.randomBytes(1)[0]%62];return t}function Te(r){return `${r}_${Ai(8)}`}function Si(r,e){let{createHash:t}=J("crypto"),n=t("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=n[i];let s="";for(let i of o)s+=Gt[i%62];return `${r}_${s}`}h();function Kt(r){let e=t=>String(t).padStart(2,"0");return `${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}T${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}h();function an(r,e){return t=>{try{let n=e(t);n instanceof Promise&&n.catch(o=>{console.error(`[crewx] event listener error (${r}): ${o instanceof Error?o.message:String(o)}`);});}catch(n){console.error(`[crewx] event listener error (${r}): ${n instanceof Error?n.message:String(n)}`);}}}var Fe=class{_emitter=new events.EventEmitter;on(e,t){let n=an(e,t);return this._emitter.on(e,n),()=>this._emitter.off(e,n)}once(e,t){let n=an(e,t);return this._emitter.once(e,n),()=>this._emitter.off(e,n)}emit(e,t){this._emitter.emit(e,t);}};h();function Xt(r){let e=new Map,t=n=>n.startsWith(`${r}::`)?n:`${r}::${n}`;return {async get(n){let o=e.get(t(n));return o?o.value:void 0},async set(n,o){e.set(t(n),{value:o});},async delete(n){return e.delete(t(n))},async list(n){let o=n?t(n):`${r}::`,s=[];for(let i of e.keys())i.startsWith(o)&&s.push(i.slice(r.length+2));return s}}}h();var Yt=new async_hooks.AsyncLocalStorage;function zi(){return Yt}function Mi(r,e){return Yt.run(r,e)}function Qt(r){let e=r.log??r.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},t=r.agentRunner??{run:async()=>({output:""})},n=r.db??{get:async()=>{},set:async()=>{},delete:async()=>false,list:async()=>[]},o=r.storage??{put:async()=>"",get:async()=>{},delete:async()=>false},s=r.audit??{log:async()=>{}},i=r.onInbound??(async()=>({accepted:true})),a=r.onEmitEvent??(async()=>({accepted:true})),l=r.onUpdateMessage??(async()=>{}),u=r.onResolveUser??(async p=>({userId:p,displayName:p})),c=async p=>{let g=Yt.getStore();if(!g){e.warn("respondSync called outside sync window \u2014 graceful degradation (no-op)",{textPreview:typeof p=="object"&&"text"in p?p.text.slice(0,80):void 0});return}let v="text"in p?p.text:"";g.res.status(200).json({text:v});},m=r.httpRouter??{registerRoute:()=>{e.warn("httpRouter not configured \u2014 registerRoute is a no-op");}};return {instanceId:r.instanceId,config:r.config,capabilities:r.capabilities,log:e,agentRunner:t,db:n,storage:o,audit:s,abortSignal:r.abortSignal??new AbortController().signal,httpRouter:m,inbound:i,emitEvent:a,updateMessage:l,resolveUser:u,respondSync:c}}h();h();h();function ae(r){return /crewx\s+(x|execute)\s/.test(r)}function le(r,e){let t=e.match(/@(\S+)/);return {timestamp:r,type:"agent_call",targetAgent:t?.[1]?.replace(/["']/g,""),toolInput:e}}function ln(r,e){let n=e.message?.content;if(!Array.isArray(n))return [];let o=[];for(let s of n){let i=ji(r,s);i&&o.push(i);}return o}function ji(r,e){let t=e.type;if(t==="text"){let n=String(e.text||"");return n?{timestamp:r,type:"text",content:n}:null}if(t==="tool_use"){let n=String(e.name||""),o=e.id,s=e.input,i=s?.command?String(s.command):JSON.stringify(s||{});return n==="Bash"&&ae(i)?le(r,i):{timestamp:r,type:"tool_use",toolUseId:o,toolName:n,toolInput:i}}if(t==="tool_result"){let n=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
49
+ `):i=JSON.stringify(s),{timestamp:r,type:"tool_result",toolUseId:o,resultPreview:i,isError:n}}return null}h();function un(r,e){let t=e.type,n=e.data;if(!n)return [];let o=n.toolCallId;if(t==="tool.execution_start"){let s=String(n.toolName||""),i=n.arguments,a=i?.command?String(i.command):JSON.stringify(i||{});return (s==="bash"||s==="Bash")&&ae(a)?[le(r,a)]:[{timestamp:r,type:"tool_use",toolName:s,toolInput:a,...o&&{toolUseId:o}}]}if(t==="tool.execution_complete"){let s=n.error;if(s)return [{timestamp:r,type:"tool_result",isError:true,resultPreview:String(s.message||""),...o&&{toolUseId:o}}];let i=n.result,a=String(i?.content||"");return [{timestamp:r,type:"tool_result",resultPreview:a,isError:false,...o&&{toolUseId:o}}]}if(t==="assistant.message"){let s=String(n.content||"");return s?[{timestamp:r,type:"text",content:s}]:[]}return []}h();function cn(r,e){let t=e.type,n=e.item;if(!n)return [];if(t==="item.started")return Ni(r,n);if(t==="item.completed"){let o=Di(r,n);return o?[o]:[]}return []}function Ni(r,e){if(e.type==="command_execution"){let n=String(e.command||"");return ae(n)?[le(r,n)]:[{timestamp:r,type:"tool_use",toolName:"Bash",toolInput:n}]}return []}function Di(r,e){let t=e.type;if(t==="message"||t==="text"){let n=e.content;if(Array.isArray(n))for(let o of n){let s=$i(r,o);if(s)return s}if(typeof e.text=="string")return {timestamp:r,type:"text",content:e.text}}if(t==="reasoning")return {timestamp:r,type:"text",content:String(e.text||"")};if(t==="command_execution"){let n=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:r,type:"tool_result",resultPreview:n,isError:o}}if(t==="tool_use"){let n=String(e.name||e.tool_name||""),o=e.input,s=o?.command?String(o.command):JSON.stringify(o||{});return n==="Bash"&&ae(s)?le(r,s):{timestamp:r,type:"tool_use",toolName:n,toolInput:s}}if(t==="tool_result"){let n=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:r,type:"tool_result",resultPreview:o,isError:n}}return null}function $i(r,e){let t=e.type;if(t==="text")return {timestamp:r,type:"text",content:String(e.text||"")};if(t==="tool_use"){let n=String(e.name||""),o=e.input,s=o?.command?String(o.command):JSON.stringify(o||{});return n==="Bash"&&ae(s)?le(r,s):{timestamp:r,type:"tool_use",toolName:n,toolInput:s}}return null}h();function Zt(r,e){let t=e.type;if(t==="message"){if(e.role!=="assistant")return [];let o=e.content;return o?[{timestamp:r,type:"text",content:o}]:[]}if(t==="tool_use"){let n=String(e.tool_name||""),o=e.tool_id,s=e.parameters,i=s?.command?String(s.command):JSON.stringify(s||{});return /^bash$/i.test(n)&&ae(i)?[le(r,i)]:[{timestamp:r,type:"tool_use",toolName:n,toolUseId:o,toolInput:i}]}if(t==="tool_result"){let n=e.tool_id,o=String(e.output||""),s=e.status!=="success";return [{timestamp:r,type:"tool_result",toolUseId:n,resultPreview:o,isError:s}]}return []}h();function er(r,e){let t=e.type;if(t==="text"){let o=e.part?.text;return o?[{timestamp:r,type:"text",content:o}]:[]}if(t==="tool_use"){let n=e.part;if(!n)return [];let o=String(n.tool||""),s=String(n.callID||""),i=n.state,a=String(i?.status||""),l=i?.input,u=Hi(l),c=[{timestamp:r,type:"tool_use",toolName:o,toolUseId:s,toolInput:u}];if(a==="completed"&&i?.output!==void 0){let m=i.output,p=typeof m=="string"?m:JSON.stringify(m);c.push({timestamp:r,type:"tool_result",toolUseId:s,resultPreview:p,isError:false});}else a==="error"&&c.push({timestamp:r,type:"tool_result",toolUseId:s,resultPreview:String(i?.error||"tool error"),isError:true});return c}return []}function Hi(r){if(typeof r=="string")return r;if(!r||typeof r!="object")return JSON.stringify(r??{});let e=r;return e.command?String(e.command):e.filePath?String(e.filePath):e.pattern?String(e.pattern):JSON.stringify(e)}function tr(r,e){let t;try{t=JSON.parse(e);}catch{return []}let n=t.type;return n?n==="assistant"||n==="user"?ln(r,t):n.startsWith("tool.execution")||n.startsWith("assistant.")||n==="user.message"?un(r,t):n.startsWith("item.")||n.startsWith("turn.")||n.startsWith("thread.")?cn(r,t):n==="message"||n==="init"?Zt(r,t):n==="tool_use"||n==="tool_result"?t.part&&typeof t.part=="object"?er(r,t):Zt(r,t):n==="text"||n==="step_start"||n==="step_finish"?er(r,t):[]:[]}h();function Li(r){return typeof r!="string"?"":r.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function rr(r){return r.messages.map(e=>({text:Li(e.text),isAssistant:e.isAssistant,metadata:e.metadata,files:void 0}))}h();h();var qi={agentId:zod.z.string().describe("The agent ID to query"),query:zod.z.string().describe("The query message to send"),context:zod.z.string().optional().describe("Additional context"),thread:zod.z.string().optional().describe("Thread ID for conversation continuity")},Fi={agentId:zod.z.string().describe("The agent ID to execute"),task:zod.z.string().describe("The task description to execute"),context:zod.z.string().optional().describe("Additional context"),thread:zod.z.string().optional().describe("Thread ID for conversation continuity")};function dn(r,e,t){r.tool("crewx_listAgents","List available CrewX agents exposed by this server",async()=>{let n=[];for(let o of t){let s=e.agents.get(o);s&&n.push({id:s.id,name:s.name??s.id,description:s.description??""});}return {content:[{type:"text",text:JSON.stringify(n,null,2)}]}}),r.tool("crewx_queryAgent","Query a CrewX agent with a read-only question",qi,async({agentId:n,query:o,context:s,thread:i})=>{if(!t.has(n))return {content:[{type:"text",text:`Agent '${n}' is not exposed by this server`}],isError:true};let a=await e.query(n,o,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Query failed"}],isError:true}}),r.tool("crewx_executeAgent","Execute a task on a CrewX agent (may modify state)",Fi,async({agentId:n,task:o,context:s,thread:i})=>{if(!t.has(n))return {content:[{type:"text",text:`Agent '${n}' is not exposed by this server`}],isError:true};let a=await e.execute(n,o,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Execute failed"}],isError:true}});}h();function pn(r){return r.headers.get("Origin")?null:new Response(JSON.stringify({error:"Forbidden: Origin header required"}),{status:403,headers:{"Content-Type":"application/json"}})}async function gn(r,e){return e?await e(r)?null:new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:{"Content-Type":"application/json"}}):null}function Wi(r,e){let t=new mcp_js.McpServer({name:"crewx-mcp-server",version:"1.0.0"},{capabilities:{tools:{}}});return dn(t,r,e),t}function nr(r,e){if(!e.agents||e.agents.length===0)throw new Error("crewx.handler() requires at least one agent in the agents option");let t=new Set(e.agents),n=new Map;return async o=>{let s=pn(o);if(s)return s;let i=await gn(o,e.auth);if(i)return i;let a=o.headers.get("mcp-session-id");if(a&&n.has(a))return n.get(a).transport.handleRequest(o);let l=Wi(r,t),u=new webStandardStreamableHttp_js.WebStandardStreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID(),onsessioninitialized:c=>{n.set(c,{transport:u,server:l});},onsessionclosed:c=>{n.delete(c);},enableJsonResponse:true});return await l.connect(u),u.handleRequest(o)}}h();h();var Ue=class{detach(e){}};h();var Ki=`
50
50
  CREATE TABLE IF NOT EXISTS threads (
51
51
  id TEXT PRIMARY KEY,
52
52
  workspace_id TEXT,
@@ -59,22 +59,23 @@ ${r??""}
59
59
  updated_at TEXT NOT NULL,
60
60
  metadata TEXT
61
61
  )
62
- `,Ui=["id","thread_id","prompt","result","started_at","trace_id","status","parent_task_id","agent_id"];function Bi(r){return r.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
62
+ `,Xi=["id","thread_id","prompt","result","started_at","trace_id","status","parent_task_id","agent_id"];function Yi(r){return r.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
63
63
  `).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
64
- `).trim()}function Wi(r){if(!r)return "";let e=r;try{let t=JSON.parse(e);Array.isArray(t)?e=t.filter(n=>n?.type==="text"&&n?.text).map(n=>n.text).join(`
65
- `):t&&typeof t=="object"&&t.result!==void 0&&(e=t.result||"");}catch{e=Bi(e);}return e}var Be=class{db;constructor(e){let t=e??X.join(os$1.homedir(),".crewx","crewx.db");this.db=new Hi__default.default(t),this.init();}init(){this.db.pragma("journal_mode = WAL"),this.db.exec(Fi);}async ensureThread(e,t,n){let o=this.db.prepare("SELECT platform FROM threads WHERE id = ?").get(e);if(o){if(o.platform!==t)throw new Error(`Thread '${e}' already exists with platform '${o.platform}' \u2014 cannot change to '${t}' (platform is immutable)`);n&&this.db.prepare("UPDATE threads SET workspace_id = COALESCE(workspace_id, ?) WHERE id = ?").run(n,e);return}let s=new Date().toISOString();this.db.prepare("INSERT INTO threads (id, platform, workspace_id, message_count, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)").run(e,t,n??null,s,s);}async fetchHistory(e,t){let n=t?.limit??100,o=["thread_id = ?","(parent_task_id IS NULL OR parent_task_id = '')","(status IN ('done', 'completed', 'success') OR status IS NULL)"],s=[e];t?.currentTraceId&&(o.push("trace_id != ?"),s.push(t.currentTraceId));let i=o.join(" AND "),l=`SELECT ${Ui.join(", ")} FROM tasks WHERE ${i} ORDER BY started_at ASC LIMIT ?`;s.push(n);let u=this.db.prepare(l).all(...s),c=this.db.prepare("SELECT platform, title, first_message, last_message, message_count, updated_at FROM threads WHERE id = ?").get(e),p=c?.platform??"cli",g=this.rowsToMessages(u);return {threadId:e,platform:p,messages:g,metadata:{title:c?.title??void 0,firstMessage:c?.first_message??void 0,lastMessage:c?.last_message??void 0,messageCount:c?.message_count??0,updatedAt:c?.updated_at?new Date(c.updated_at).getTime():void 0}}}async saveUserMessage(e,t,n,o){let s=new Date().toISOString();this.db.prepare(`UPDATE threads
64
+ `).trim()}function Qi(r){if(!r)return "";let e=r;try{let t=JSON.parse(e);Array.isArray(t)?e=t.filter(n=>n?.type==="text"&&n?.text).map(n=>n.text).join(`
65
+ `):t&&typeof t=="object"&&t.result!==void 0&&(e=t.result||"");}catch{e=Yi(e);}return e}var Be=class{db;constructor(e){let t=e??X.join(os.homedir(),".crewx","crewx.db");this.db=new Ji__default.default(t),this.init();}init(){this.db.pragma("journal_mode = WAL"),this.db.exec(Ki),this.migrateThreadsTable();}migrateThreadsTable(){this.db.prepare("PRAGMA table_info(threads)").all().some(t=>t.name==="title_locked")||this.db.exec("ALTER TABLE threads ADD COLUMN title_locked INTEGER NOT NULL DEFAULT 0");}updateThread(e,t){t.title!==void 0&&this.db.prepare("UPDATE threads SET title = ?, title_locked = 1, updated_at = ? WHERE id = ?").run(t.title,new Date().toISOString(),e);}async ensureThread(e,t,n){let o=this.db.prepare("SELECT platform FROM threads WHERE id = ?").get(e);if(o){if(o.platform!==t)throw new Error(`Thread '${e}' already exists with platform '${o.platform}' \u2014 cannot change to '${t}' (platform is immutable)`);n&&this.db.prepare("UPDATE threads SET workspace_id = COALESCE(workspace_id, ?) WHERE id = ?").run(n,e);return}let s=new Date().toISOString();this.db.prepare("INSERT INTO threads (id, platform, workspace_id, message_count, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?)").run(e,t,n??null,s,s);}async fetchHistory(e,t){let n=t?.limit??100,o=["thread_id = ?","(parent_task_id IS NULL OR parent_task_id = '')","(status IN ('done', 'completed', 'success') OR status IS NULL)"],s=[e];t?.currentTraceId&&(o.push("trace_id != ?"),s.push(t.currentTraceId));let i=o.join(" AND "),l=`SELECT ${Xi.join(", ")} FROM tasks WHERE ${i} ORDER BY started_at ASC LIMIT ?`;s.push(n);let u=this.db.prepare(l).all(...s),c=this.db.prepare("SELECT platform, title, first_message, last_message, message_count, updated_at FROM threads WHERE id = ?").get(e),m=c?.platform??"cli",p=this.rowsToMessages(u);return {threadId:e,platform:m,messages:p,metadata:{title:c?.title??void 0,firstMessage:c?.first_message??void 0,lastMessage:c?.last_message??void 0,messageCount:c?.message_count??0,updatedAt:c?.updated_at?new Date(c.updated_at).getTime():void 0}}}async saveUserMessage(e,t,n,o){let s=new Date().toISOString();this.db.prepare(`UPDATE threads
66
66
  SET first_message = COALESCE(first_message, ?),
67
+ title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(?, 1, 60) ELSE title END,
67
68
  last_message = ?,
68
69
  message_count = message_count + 1,
69
70
  updated_at = ?
70
- WHERE id = ?`).run(t,t,s,e);}async saveAssistantMessage(e,t,n,o){let s=new Date().toISOString();this.db.prepare(`UPDATE threads
71
+ WHERE id = ?`).run(t,t,t,s,e);}async saveAssistantMessage(e,t,n,o){let s=new Date().toISOString();this.db.prepare(`UPDATE threads
71
72
  SET last_message = ?,
72
73
  updated_at = ?
73
- WHERE id = ?`).run(t,s,e);}close(){this.db.close();}rowsToMessages(e){let t=[];for(let n of e){n.prompt&&t.push({id:`${n.id}-user`,text:n.prompt,isAssistant:false,timestamp:new Date(n.started_at).getTime()});let o=Wi(n.result);o&&t.push({id:`${n.id}-assistant`,text:o,isAssistant:true,timestamp:new Date(n.started_at).getTime()});}return t}};var We=class extends Ue{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Be(e?.dbPath);}get conversationProvider(){return this._provider}attach(e){this.unsubStart=e.on("task:start",async t=>{if(!t.threadId)return;let n=t.platform??"cli";try{await this._provider.ensureThread(t.threadId,n,t.workspaceId),await this._provider.saveUserMessage(t.threadId,t.message??"");}catch{}}),this.unsubEnd=e.on("task:end",async t=>{if(!t.result)return;let n=t.metadata?.threadId;if(!n)return;let o=t.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(n,t.result,o);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};y();function un(r){let e=X__namespace.resolve(r);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,n)=>`${n.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function er(r){let e=un(r);return crypto$1.createHash("sha256").update(e).digest("hex")}function Gc(r){return r?r.settings?.template?.exec:void 0}function Xc(){try{let r=new Uint8Array(8);return globalThis.crypto.getRandomValues(r),Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}catch{let{randomBytes:r}=U("crypto");return r(8).toString("hex")}}var Er=class r extends Fe{_agents;_templateEngine;_documentLoader;_layoutLoader;_layoutRenderer;_config;_projectRoot;_workspaceId;_workspaceName;_plugins=[];_tools=new Map;_activeAdapters=new Map;_pendingThreads=new Map;_remoteFactory;_remoteTargets=new Map;constructor(e,t={},n,o,s){super(),this._agents=new Map(e.map(l=>[l.id,l])),this._config=n,this._projectRoot=s??(typeof process<"u"?process.cwd():"/");let i=s??(typeof process<"u"?process.env.CREWX_WORKSPACE??process.cwd():"/");this._workspaceId=er(i),this._workspaceName=X.basename(i);let a=Gc(n);this._templateEngine=new De({execPolicy:t.execPolicy??a}),this._documentLoader=o??new Ce,this._layoutLoader=new He({templatesPath:Se()}),this._layoutRenderer=new qe,this._remoteFactory=t.remoteFactory;}async resolveFileRemoteTarget(e){let t=this.getAgent(e),n=Array.isArray(t?.provider)?t?.provider[0]:t?.provider;if(!n?.startsWith("remote/"))return null;let o=n.slice(7),s=this.getRemoteProviderConfig(o);if(!s?.location?.startsWith("file://"))return null;let i=X.resolve(s.location.replace("file://","")),a=s.external_agent_id??e.replace(/^@/,""),l=this._remoteTargets.get(i);l||(l=(this._remoteFactory??(m=>r.loadYaml(m)))(i),this._remoteTargets.set(i,l),l.catch(()=>this._remoteTargets.delete(i)));let u=await l,c=u.getAgent("@"+a),p=Array.isArray(c?.provider)?c?.provider[0]:c?.provider;if(p?.startsWith("remote/"))throw new Error(`Chained remotes not allowed: "${o}" \u2192 "${p}"`);return {target:u,agentRef:"@"+a}}static async loadBuiltInConfig(e){let{yamlPath:t,dir:n}=Mt(),o;try{o=fs$1.readFileSync(t,"utf-8");}catch(i){throw new Error(`[@crewx/sdk] Cannot read built-in config: ${t}
74
- ${i.message}`)}let s=ut(o);if(s.documents&&typeof s.documents=="object"){let i={};for(let[a,l]of Object.entries(s.documents))if(l&&typeof l=="object"){let u=l;typeof u.path=="string"&&!X.isAbsolute(u.path)?i[a]={...u,path:X.resolve(n,u.path)}:i[a]=u;}else i[a]=l;return {...s,documents:i}}return s}static mergeCrewxConfig(e,t){let n=new Map;for(let _ of e.agents??[])n.set(_.id,_);for(let _ of t.agents??[])n.has(_.id)&&console.warn(`[agent-loader] User agent "${_.id}" overrides built-in`),n.set(_.id,_);let o=Array.from(n.values()),s={...e.layouts??{},...t.layouts??{}},i={...e.documents??{},...t.documents??{}},a=e,l=t,u=ps(a.vars,l.vars),c=ps(a.settings,l.settings),p;e.skills&&t.skills&&typeof e.skills=="object"&&typeof t.skills=="object"&&!Array.isArray(e.skills)&&!Array.isArray(t.skills)?p={...e.skills,...t.skills}:p=t.skills??e.skills;let g=[...e.hooks??[],...t.hooks??[]],m=Yc(a.providers,l.providers),v={...e},f={...t};for(let _ of ["agents","layouts","documents","skills","hooks","vars","settings","providers"])delete v[_],delete f[_];let h={...{...v,...f},agents:o,layouts:s,documents:i,skills:p};return g.length>0&&(h.hooks=g),u!==void 0&&(h.vars=u),c!==void 0&&(h.settings=c),m!==void 0&&(h.providers=m),h}static async loadYaml(e,t,n){let o=t?.includeBuiltIns!==false,s,i;if(o){let c=await r.loadBuiltInConfig(n);if(e!==void 0){let p=ct(e);s=r.mergeCrewxConfig(c,p),i=X.dirname(e);}else s=c,i=process.cwd();}else {if(e===void 0)throw new Error("[@crewx/sdk] loadYaml: path is required when includeBuiltIns is false");s=ct(e),i=X.dirname(e);}let a=new Ce(n);await a.load(s.documents,i);let l=s.agents??[];await gs(l,s,t);let u=new r(l,t??{},s,a,i);return await u.use(new We),u}static async fromConfig(e,t,n,o){let s=t?.includeBuiltIns===true,i=e;if(s){let c=await r.loadBuiltInConfig(o);i=r.mergeCrewxConfig(c,e);}let a=new Ce(o);await a.load(i.documents,n??(typeof process<"u"?process.cwd():"/"));let l=i.agents??[];await gs(l,i,t);let u=new r(l,t??{},i,a,n);return await u.use(new We),u}get agents(){return this._agents}get config(){return this._config}get plugins(){return this._plugins}get tools(){return this._tools}get workspaceId(){return this._workspaceId}get workspaceName(){return this._workspaceName}getAgent(e){let t=e.startsWith("@")?e.slice(1):e;return this._agents.get(t)}getRemoteProviderConfig(e){let t=this._config?.providers;return Array.isArray(t)?t.find(o=>o.type==="remote"&&o.id===e):void 0}computeTaskLogPath(e,t){let n=Wt(t);return X.join(this._projectRoot,".crewx","logs",`${n}_${e}.log`)}registerTool(e,t){this._tools.set(e,{name:e,...t});}async use(e){this._plugins.includes(e)||(await e.attach(this),this._plugins.push(e));}handler(e){return Zt(this,e)}async registerChannelAdapter(e){let{adapter:t,instanceId:n,config:o}=e;if(this._activeAdapters.has(n))throw new Error(`Adapter instance already registered: ${n}`);let s=new Set(t.manifest.capabilities),i=e.store??Jt(n),a=e.defaultMode??"query",l=t.manifest.platform,u=e.agentRunner??{run:async(m,v,f)=>{let h=await(a==="execute"?this.execute.bind(this):this.query.bind(this))(`@${m}`,v,{threadId:f?.threadId,platform:l});return {output:h.ok?h.data:h.error?.message??""}}},c=e.onInbound??(async m=>{let v=m.routingHints?.agentId??e.defaultAgent;if(!v)return {accepted:false,reason:"no_agent"};let{output:f}=await u.run(v,m.text,{threadId:m.threadId});return {accepted:true,output:f}}),p=Kt({instanceId:n,config:o,capabilities:s,db:i,agentRunner:u,onInbound:c}),g={adapter:t,ctx:p,state:"starting"};this._activeAdapters.set(n,g),this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"starting",timestamp:new Date});try{await t.start(p),g.state="started",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"started",timestamp:new Date});}catch(m){throw g.state="failed",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"failed",error:m instanceof Error?m:new Error(String(m)),timestamp:new Date}),this._activeAdapters.delete(n),m}}async unregisterChannelAdapter(e){let t=this._activeAdapters.get(e);if(t){t.state="stopping",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopping",timestamp:new Date});try{await t.adapter.stop(t.ctx),t.state="stopped",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopped",timestamp:new Date});}catch(n){t.state="failed",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"failed",error:n instanceof Error?n:new Error(String(n)),timestamp:new Date});}finally{this._activeAdapters.delete(e);}}}async stopAllAdapters(e={}){let t=e.timeoutMs??1e4,n=Array.from(this._activeAdapters.keys()),o=await Promise.allSettled(n.map(s=>Promise.race([this.unregisterChannelAdapter(s),new Promise((i,a)=>setTimeout(()=>a(new Error(`Adapter stop timeout: ${s}`)),t))])));for(let s=0;s<o.length;s++)o[s].status==="rejected"&&console.error(`[crewx] adapter stop error (${n[s]}): ${o[s].reason}`);}async close(){await this.stopAllAdapters({timeoutMs:1e4});let e=[...this._remoteTargets.values()];this._remoteTargets.clear(),await Promise.allSettled(e.map(async n=>{try{await(await n).close();}catch(o){console.error(`[crewx] remote target close error: ${o instanceof Error?o.message:String(o)}`);}}));let t=[...this._plugins].reverse();for(let n of t)try{await n.detach(this);}catch(o){console.error(`[crewx] plugin ${n.name} detach error: ${o instanceof Error?o.message:String(o)}`);}this._plugins.length=0;}filterAgents(e){let t=a=>a?a.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,n=t(e.role),o=t(e.team),s=t(e.provider),i=Array.from(this._agents.values());return n&&(i=i.filter(a=>a.role&&n.some(l=>se(a.role.toLowerCase(),l)))),o&&(i=i.filter(a=>a.team&&o.some(l=>se(a.team.toLowerCase(),l)))),s&&(i=i.filter(a=>(Array.isArray(a.provider)?a.provider:[a.provider]).some(u=>s.some(c=>se(u.toLowerCase(),c))))),i}renderAgentPrompt(e){let t=e.startsWith("@")?e.slice(1):e,n=this._agents.get(t);if(!n)throw new de(t,Array.from(this._agents.keys()));return n.inline?.prompt??n.inline?.system_prompt??n.description??`You are an expert ${t}.`}async renderPrompt(e,t){let o={...await this._documentLoader.buildContext(),...t?.documents??{}},s={...t,documents:o};return this._templateEngine.render(e,s)}registerLayout(e,t){this._layoutLoader.registerLayout(e,t);}async renderAgentPromptFull(e,t){let n=e.startsWith("@")?e.slice(1):e,o=this._agents.get(n);if(!o)throw new de(n,Array.from(this._agents.keys()));let s=this._resolveLayoutSpec(o,t?.layout),i=this._extractLayoutId(s),a=this._extractLayoutProps(o,s,t?.layout),l=this._layoutLoader.load(i,a),u=o.inline?.prompt??o.inline?.system_prompt??o.description??`You are an expert ${n}.`,c=await this._documentLoader.buildContext(),p=t?.env??(typeof process<"u"?process.env:{}),g=t?.vars?.security_key??Xc(),m={...t?.vars??{},documents:c,env:p,agent:{id:o.id,name:o.name??o.id,role:o.role??"",team:o.team??"",description:o.description??""}},v=await this._templateEngine.render(u,m),f={mode:t?.session?.mode??"query",platform:t?.session?.platform??"cli",options:t?.session?.options??[]},d=o.provider,h=Array.isArray(d)?d:typeof d=="string"&&d.length>0?[d]:[],_=h.join(", ")||(typeof d=="string"?d:""),C=o.options,w=!Array.isArray(C)&&typeof C=="object"&&C!==null?C:void 0,x=Array.isArray(C)?C:void 0,S={};for(let[k,O]of Object.entries(c))S[k]={content:O.content??"",toc:O.toc,summary:O.summary,path:O.path};let T={user_input:t?.vars?.user_input??void 0,agent:{id:o.id,name:o.name??o.id,role:o.role??"",team:o.team??"",description:o.description??"",provider:_,providerList:h,model:o.inline?.model,workingDirectory:o.working_directory??o.workingDirectory??".",inline:{...o.inline??{},prompt:v},specialties:o.specialties??[],capabilities:o.capabilities??[],remote:o.remote??null,optionsByMode:w,optionsArray:x},agentMetadata:{specialties:o.specialties??[],capabilities:o.capabilities??[],description:o.description??""},documents:S,skills:t?.skills??[],session:f,env:p,vars:{security_key:g,...t?.vars??{}},props:{...a??{},...t?.messages&&t.messages.length>0?{showConversationHistory:true}:{}},platform:f.platform,mode:f.mode,messages:t?.messages??[],tools:this._tools.size>0?{list:Array.from(this._tools.values()).map(k=>({name:k.name,description:k.description,parameters:k.parameters})),json:JSON.stringify(Array.from(this._tools.values()).map(k=>({name:k.name,description:k.description,parameters:k.parameters})),null,2),count:this._tools.size}:null,metadata:{}};return this._layoutRenderer.render(l,T)}_filterToolsByMode(e){return e?e.map(t=>this._tools.get(t)).filter(t=>t!==void 0):Array.from(this._tools.values())}_resolveLayoutSpec(e,t){if(t!==void 0)return t;let n=e.inline?.layout;if(n!==void 0)return n;let o=this._config?.layouts?.default;return typeof o=="string"&&o?o:"crewx/default"}_extractLayoutId(e){if(typeof e=="string")return e;if("id"in e)return e.id;let t=`crewx/__inline_${Date.now()}`;return this._layoutLoader.registerLayout(t,e.template),t}_extractLayoutProps(e,t,n){let o=e.inline?.layout,s=o&&typeof o=="object"&&"props"in o?o.props:void 0,i=n&&typeof n=="object"&&"id"in n?n.props:void 0;if(s||i)return {...s??{},...i??{}}}_getConversationProvider(){return this._plugins.find(t=>t.name==="conversation")?.conversationProvider}async _fetchHistoryMessages(e,t,n){if(n&&n.length>0)return n;if(!e)return;let o=this._getConversationProvider();if(o)try{let s=await o.fetchHistory(e,{currentTraceId:t});return s.messages.length===0?void 0:Qt(s)}catch{return}}emitToolEvents(e,t,n,o,s,i,a){try{let l=Yt(new Date().toISOString(),o);for(let u of l)u.type==="tool_use"&&u.toolName&&this.emit("tool:observed:before",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:n,tool:{name:u.toolName,rawName:u.toolName,input:u.toolInput?this.tryParseJson(u.toolInput):void 0,toolUseId:u.toolUseId}}),u.type==="tool_result"&&this.emit("tool:observed:after",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:n,tool:{name:u.toolName??"unknown",rawName:u.toolName??"unknown",toolUseId:u.toolUseId,result:u.resultPreview,isError:u.isError}});}catch{}}tryParseJson(e){try{return JSON.parse(e)}catch{return e}}async query(e,t,n){let o=await this.resolveFileRemoteTarget(e);if(o)return o.target.query(o.agentRef,t,n);let s=Date.now(),i=Te("tsk"),a=new Date,l;try{l=pt(e,Array.from(this._agents.values()));}catch(k){if(k instanceof de){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let O=Date.now()-s,I={code:"AGENT_NOT_FOUND",message:k.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:O,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:O}}}throw k}let u=Array.isArray(l.provider)?l.provider[0]??"cli/claude":l.provider,c=n?.provider??u,p=n?.model??l.inline?.model,g;try{g=pe(c);}catch(k){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let O=Date.now()-s,I={code:"PROVIDER_ERROR",message:k.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:O,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:p,durationMs:O}}}let m=await this._fetchHistoryMessages(n?.threadId,i,n?.messages),v;try{v=await this.renderAgentPromptFull(e,{session:{mode:"query",platform:n?.platform},vars:{user_input:t},messages:m});}catch{}let f,d,h,_=p,C=false,w=k=>{C||(C=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",pid:k,model:_,provider:c,codingAgentCommand:f,renderedPrompt:v,metadata:{...n?.metadata??{},provider:c},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},x=l.options,S=Array.isArray(x?.query?.tools)?x.query.tools:void 0,z=this._tools.size>0?this._filterToolsByMode(S):[],T=l.inline?.max_steps;c.startsWith("api/")&&w();try{let k=await g.query(t,{model:p,context:n?.context,systemPrompt:v??l.inline?.system_prompt??l.inline?.prompt,additionalArgs:Array.isArray(x?.query)?x.query:void 0,tools:z.length>0?z:void 0,maxSteps:T,env:{CREWX_AGENT_ID:l.id,CREWX_AGENT_ROLE:l.role??"",CREWX_AGENT_TEAM:l.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:n?.threadId??"",CREWX_PROVIDER:c,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:I=>w(I),onOutput:(I,W)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:I,level:W}),W==="stdout"&&this.emitToolEvents(i,e,c,I,l.id,n?.threadId??"","");},onCommand:I=>{f=I;},onUsage:I=>{d=I;},onExitCode:I=>{h=I;},onModel:I=>{_||(_=I);}});w();let O=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",result:k,durationMs:O,exitCode:h,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:_,metadata:{...n?.metadata??{},...n?.threadId?{threadId:n.threadId}:{}}}),{ok:!0,data:k,meta:{agentId:l.id,provider:c,model:p,durationMs:O}}}catch(k){if(k instanceof exports.ClientToolCallRequiredError){let W=Te("thd");return this._pendingThreads.set(W,{agentRef:l.id,providerStr:c,continuationState:k.continuationState,toolCall:k.toolCall,traceId:i,startMs:s,model:p}),{ok:true,status:"requires_action",data:"",toolCall:k.toolCall,threadId:W,meta:{agentId:l.id,provider:c,model:p,durationMs:Date.now()-s}}}w();let O=Date.now()-s,I={code:"QUERY_FAILED",message:k.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:O,error:I,exitCode:h,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:_,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:p,durationMs:O}}}}async continueQuery(e,t){let n=this._pendingThreads.get(e);if(!n)return {ok:false,data:"",error:{code:"THREAD_NOT_FOUND",message:`No pending thread: ${e}`},meta:{agentId:"",provider:"",durationMs:0}};this._pendingThreads.delete(e);let o=pe(n.providerStr);if(!o.continueWithToolResults)return {ok:false,data:"",error:{code:"UNSUPPORTED",message:"Provider does not support client tool continuation"},meta:{agentId:n.agentRef,provider:n.providerStr,durationMs:0}};let s=t.map(i=>({...i,toolName:n.toolCall.toolCallId===i.toolCallId?n.toolCall.toolName:i.toolCallId}));try{let i=await o.continueWithToolResults(n.continuationState,s),a=Date.now()-n.startMs;return this.emit("task:end",{traceId:n.traceId,timestamp:new Date,agentRef:n.agentRef,mode:"query",result:i,durationMs:a}),{ok:!0,status:"complete",data:i,meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:a}}}catch(i){if(i instanceof exports.ClientToolCallRequiredError)return this._pendingThreads.set(e,{...n,continuationState:i.continuationState,toolCall:i.toolCall}),{ok:true,status:"requires_action",data:"",toolCall:i.toolCall,threadId:e,meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:Date.now()-n.startMs}};let a=Date.now()-n.startMs;return {ok:false,data:"",error:{code:"CONTINUE_FAILED",message:i.message},meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:a}}}}async execute(e,t,n){let o=await this.resolveFileRemoteTarget(e);if(o)return o.target.execute(o.agentRef,t,n);let s=Date.now(),i=Te("tsk"),a=new Date,l;try{l=pt(e,Array.from(this._agents.values()));}catch(k){if(k instanceof de){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let O=Date.now()-s,I={code:"AGENT_NOT_FOUND",message:k.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:O,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:O}}}throw k}let u=Array.isArray(l.provider)?l.provider[0]??"cli/claude":l.provider,c=n?.provider??u,p=n?.model??l.inline?.model,g;try{g=pe(c);}catch(k){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let O=Date.now()-s,I={code:"PROVIDER_ERROR",message:k.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:O,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:p,durationMs:O}}}let m=await this._fetchHistoryMessages(n?.threadId,i,n?.messages),v;try{v=await this.renderAgentPromptFull(e,{session:{mode:"execute",platform:n?.platform},vars:{user_input:t},messages:m});}catch{}let f,d,h,_=p,C=false,w=k=>{C||(C=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",pid:k,model:_,provider:c,codingAgentCommand:f,renderedPrompt:v,metadata:{...n?.metadata??{},provider:c},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},x=l.options,S=Array.isArray(x?.execute?.tools)?x.execute.tools:void 0,z=this._tools.size>0?this._filterToolsByMode(S):[],T=l.inline?.max_steps;c.startsWith("api/")&&w();try{let k=await g.execute(t,{model:p,context:n?.context,systemPrompt:v??l.inline?.system_prompt??l.inline?.prompt,additionalArgs:Array.isArray(x?.execute)?x.execute:void 0,tools:z.length>0?z:void 0,maxSteps:T,env:{CREWX_AGENT_ID:l.id,CREWX_AGENT_ROLE:l.role??"",CREWX_AGENT_TEAM:l.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:n?.threadId??"",CREWX_PROVIDER:c,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:I=>w(I),onOutput:(I,W)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:I,level:W}),W==="stdout"&&this.emitToolEvents(i,e,c,I,l.id,n?.threadId??"","");},onCommand:I=>{f=I;},onUsage:I=>{d=I;},onExitCode:I=>{h=I;},onModel:I=>{_||(_=I);}});w();let O=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",result:k,durationMs:O,exitCode:h,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:_,metadata:{...n?.metadata??{},...n?.threadId?{threadId:n.threadId}:{}}}),{ok:!0,data:k,meta:{agentId:l.id,provider:c,model:p,durationMs:O}}}catch(k){w();let O=Date.now()-s,I={code:"EXECUTE_FAILED",message:k.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:O,error:I,exitCode:h,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:_,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:p,durationMs:O}}}}};function ps(r,e){let t=Ar(r)?r:void 0,n=Ar(e)?e:void 0;if(!(!t&&!n))return {...t??{},...n??{}}}function Ar(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Yc(r,e){let t=Array.isArray(r)?r:void 0,n=Array.isArray(e)?e:void 0;if(!t&&!n)return;let o=a=>{if(!Ar(a))return;let l=a.id;if(typeof l=="string")return `id:${l}`;let u=a.name;if(typeof u=="string")return `name:${u}`},s=new Set;for(let a of n??[]){let l=o(a);l&&s.add(l);}let i=[];for(let a of t??[]){let l=o(a);l&&s.has(l)||i.push(a);}for(let a of n??[])i.push(a);return i}async function gs(r,e,t){if(r.some(o=>(Array.isArray(o.provider)?o.provider:[o.provider]).some(i=>i.startsWith("api/")))){let{registerApiProviders:o}=await Promise.resolve().then(()=>(kr(),ns));o(t?.api);}Qc(r,e),Zc(r,e);}function Qc(r,e){if(!r.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(l=>l.startsWith("remote/"))))return;let n=e.providers;if(!Array.isArray(n))return;let{createRemoteProviderFactory:o}=(Tr(),Dr(ss)),s=new Map;for(let i of n)i.type==="remote"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&Ie("remote",o(s,pe));}function Zc(r,e){if(!r.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(l=>l.startsWith("plugin/"))))return;let n=e.providers;if(!Array.isArray(n))return;let{createPluginProviderFactory:o}=(Pr(),Dr(us)),s=new Map;for(let i of n)i.type==="plugin"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&Ie("plugin",o(s));}y();var ed="crewx:fs:",Sr=class{prefix;store;constructor(e){this.prefix=e?.prefix??ed,this.store=e?.storage??new Map;}async readFile(e){let t=this.toKey(e),n=this.store.get(t);if(n===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return n}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let t=e.map(i=>i.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),n=t.split("/"),o=[];for(let i of n)i==="."||i===""||(i===".."?o.pop():o.push(i));let s=o.join("/");return t.startsWith("/")?`/${s}`:s}isAbsolute(e){return e.startsWith("/")}setItem(e,t){this.store.set(this.toKey(e),t);}removeItem(e){this.store.delete(this.toKey(e));}keys(){return Array.from(this.store.keys()).filter(e=>e.startsWith(this.prefix)).map(e=>e.slice(this.prefix.length))}toKey(e){return `${this.prefix}${e.replace(/\\/g,"/")}`}};Re();xr();kr();y();var Ir=0;function td(r){let e=Array.from(r.agents.keys());return {name:"delegate_to_agent",description:`Delegate a task to another agent. Available agents: ${e.join(", ")}`,parameters:{type:"object",properties:{agent:{type:"string",description:`Agent ID to delegate to. One of: ${e.join(", ")}`},message:{type:"string",description:"Task description for the target agent"},mode:{type:"string",description:'Execution mode: "query" for questions, "execute" for actions. Default: query'}},required:["agent","message"]},execute:async t=>{if(Ir>=3)return "Error: Maximum delegation depth (3) reached. Cannot delegate further.";let n=t.agent,o=t.message,s=t.mode??"query";if(!e.includes(n))return `Error: Unknown agent "${n}". Available: ${e.join(", ")}`;Ir++;try{if(s==="execute"){let a=await r.execute(n,o);return a.ok?a.data:`Error: ${a.error?.message??"Unknown error"}`}let i=await r.query(n,o);return i.ok?i.data:`Error: ${i.error?.message??"Unknown error"}`}finally{Ir--;}}}}y();var ms=typeof process<"u"?process.env:{};function rd(){return ms.CREWX_CLI||"npx crewx"}function nd(){return ms.CREWX_WORKSPACE||(typeof process<"u"?process.cwd():"/")}y();var od=/^[a-zA-Z0-9._-]+$/,Or=class{constructor(e){this.storage=e;}storage;listBoxes(e){this.validateId(e);let n=this.storage.listBoxes(e).map(o=>this.toBoxResponse(o));return {boxes:n,total:n.length}}getBox(e,t){this.validateId(e),this.validateId(t);let n=this.storage.findBox(e,t);return n?this.toBoxResponse(n):null}createBox(e,t){this.validateId(e);let n=this.generateBoxId(),o=new Date().toISOString(),s=this.storage.insertBox(e,{id:n,seq:t.seq,firstTaskId:t.firstTaskId,midTaskId:t.midTaskId,lastTaskId:t.lastTaskId,taskCount:t.taskCount,summary:t.summary??null,sourceTokens:t.sourceTokens,summaryTokens:t.summaryTokens??null,createdAt:o});return this.toBoxResponse(s)}toBoxResponse(e){return {id:e.id,threadId:e.thread_id,seq:e.seq,firstTaskId:e.first_task_id,lastTaskId:e.last_task_id,taskCount:e.task_count,sourceTokens:e.source_tokens,summaryTokens:e.summary_tokens,summary:e.summary,previewFirst:this.storage.getTaskPreview(e.first_task_id,200),previewMid:this.storage.getTaskPreview(e.mid_task_id,200),previewLast:this.storage.getTaskPreview(e.last_task_id,200),createdAt:e.created_at}}validateId(e){if(!od.test(e))throw new Error(`Invalid ID format: ${e}`)}generateBoxId(){return Te("box")}};y();function sd(r,e,t,n,o){let{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}=n,l=s*i,u=s*a,c=l+u,p=e.getThreadMessages(r),g=[],m=0,v=false,f=[];for(let _=0;_<p.length;_+=2){let C=p[_],w=p[_+1],x=C?.content||"",S=w?.content||"",z=o.countTokens(x+S),T=[];C&&T.push(C),w&&T.push(w),f.push({messages:T,tokens:z});}for(let _=f.length-1;_>=0;_--){let C=f[_];if(m+C.tokens>l){v=true;break}m+=C.tokens,g.unshift(...C.messages);}let d=[],h=0;if(v&&u>0)try{let{boxes:_}=t.listBoxes(r);for(let C=_.length-1;C>=0;C--){let w=_[C],x=w.summaryTokens??w.sourceTokens;if(h+x>u)break;h+=x,d.unshift({boxId:w.id,seq:w.seq,taskCount:w.taskCount,sourceTokens:w.sourceTokens,summary:w.summary,previewFirst:w.previewFirst,previewMid:w.previewMid,previewLast:w.previewLast,createdAt:w.createdAt});}}catch(_){if(_ instanceof Error&&!/not found/i.test(_.message))throw _}return {hot:g,warm:d,hotTokens:m,warmTokens:h,hotOverflow:v,totalBudget:c,config:{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}}}Nt();y();var St=class extends Error{constructor(t,n){super(`Task ${t} timed out after ${n}ms`);this.taskId=t;this.timeoutMs=n;this.name="ParallelRunnerTimeoutError";}taskId;timeoutMs},at=class{constructor(e={}){this.defaults=e;}defaults;metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0};async run(e,t={}){if(!Array.isArray(e))throw new TypeError("ParallelRunner.run expects an array of tasks");if(e.length===0)return this.metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0},[];let n=this.mergeOptions(t),o=Math.max(1,n.maxConcurrency??5),s=n.timeoutMs,i=n.failFast??false,a=n.callbacks,l=n.evaluateTaskSuccess??(()=>true),u=[],c=0,p=0,g=0,m=false,v=0,f=perf_hooks.performance.now(),d=async T=>{a?.onTaskStart&&await a.onTaskStart(T),g+=1;let k=new AbortController,O={signal:k.signal},I,W;typeof s=="number"&&Number.isFinite(s)&&s>0&&(W=new Promise((te,ne)=>{I=setTimeout(()=>{let q=new St(T.id,s);k.abort(q),ne(q);},s);}));let G=perf_hooks.performance.now(),H=T.run(O),be=W?Promise.race([H,W]):H;try{let te=await be,ne=perf_hooks.performance.now(),q=ne-G,Y=l(te,T),J={taskId:T.id,success:Y,value:te,durationMs:q,startedAt:G,finishedAt:ne,metadata:T.metadata,aborted:!1};u.push(J),Y?c+=1:p+=1,a?.onTaskComplete&&await a.onTaskComplete(J),i&&!Y&&(m=!0);}catch(te){let ne=perf_hooks.performance.now(),q=ne-G,Y=te instanceof Error?te:new Error(String(te)),J={taskId:T.id,success:false,error:Y,durationMs:q,startedAt:G,finishedAt:ne,metadata:T.metadata,aborted:k.signal.aborted};u.push(J),p+=1,a?.onError&&await a.onError(T,Y,q),i&&(m=true);}finally{I&&clearTimeout(I),W&&H.catch(()=>{});}},h=async()=>{for(;!m;){let T=v;if(T>=e.length)break;v+=1;let k=e[T];if(!k||(await d(k),m))break}},_=Math.min(o,e.length),C=[];for(let T=0;T<_;T++)C.push(h());await Promise.all(C);let x=perf_hooks.performance.now()-f,S=u.length?u.reduce((T,k)=>T+k.durationMs,0)/u.length:0,z=x>0?u.length/(x/1e3):u.length;return this.metrics={totalTasks:e.length,startedTasks:g,completedTasks:u.length,successCount:c,failureCount:p,totalDurationMs:x,averageDurationMs:S,throughput:z},u}getMetrics(){return this.metrics}mergeOptions(e){return {maxConcurrency:e.maxConcurrency??this.defaults.maxConcurrency,timeoutMs:e.timeoutMs??this.defaults.timeoutMs,failFast:e.failFast??this.defaults.failFast,evaluateTaskSuccess:e.evaluateTaskSuccess??this.defaults.evaluateTaskSuccess,callbacks:this.mergeCallbacks(this.defaults.callbacks,e.callbacks)}}mergeCallbacks(e,t){if(!(!e&&!t))return {onTaskStart:async n=>{e?.onTaskStart&&await e.onTaskStart(n),t?.onTaskStart&&await t.onTaskStart(n);},onTaskComplete:async n=>{e?.onTaskComplete&&await e.onTaskComplete(n),t?.onTaskComplete&&await t.onTaskComplete(n);},onError:async(n,o,s)=>{e?.onError&&await e.onError(n,o,s),t?.onError&&await t.onError(n,o,s);}}}};y();y();var lt=class{async query(e){throw new Error("AgentRuntime.query is not implemented. Provide a subclass or mock AgentRuntime.prototype.query.")}async execute(e){throw new Error("AgentRuntime.execute is not implemented. Provide a subclass or mock AgentRuntime.prototype.execute.")}};var fs=3,hs=3e4,ys=500,id=r=>{if(typeof r!="number"||Number.isNaN(r)||!Number.isFinite(r))return fs;let e=Math.floor(r);return e>0?e:fs},ad=r=>r===void 0||typeof r!="number"||Number.isNaN(r)||r<=0?hs:r,ld=r=>{if(!r)return {maxRetries:0,retryDelay:ys};let e=Number.isInteger(r.maxRetries)&&r.maxRetries>=0?r.maxRetries:0,t=typeof r.retryDelay=="number"&&r.retryDelay>=0?r.retryDelay:ys;return {maxRetries:e,retryDelay:t}},zr=r=>{let e=r.reason;return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("Parallel operation aborted")},ud=(r,e)=>r<=0?Promise.resolve():new Promise((t,n)=>{let o=setTimeout(()=>{e.removeEventListener("abort",s),t();},r),s=()=>{clearTimeout(o),n(zr(e));};if(e.aborted){s();return}e.addEventListener("abort",s,{once:true});}),cd=async(r,e,t)=>{let n,o;for(let s=0;s<=e.maxRetries;s++){if(t.aborted)throw zr(t);try{let i=await r();if(n=i,i.success||s===e.maxRetries)return i}catch(i){if(o=i,t.aborted)throw zr(t);if(s===e.maxRetries)throw i instanceof Error?i:new Error(String(i))}s<e.maxRetries&&await ud(e.retryDelay,t);}if(n)return n;throw o?o instanceof Error?o:new Error(String(o)):new Error("Parallel helper encountered an unexpected state")},vs=(r,e,t)=>{e.completed+=1,t?e.success+=1:e.failure+=1;try{r.onProgress?.(e.completed,e.total);}catch(n){process.env.NODE_ENV!=="production"&&console.warn("Parallel helper onProgress callback threw an error:",n);}},dd=r=>r.map(t=>({metadata:t.metadata,taskResult:t})).slice().sort((t,n)=>t.metadata.index-n.metadata.index).map(({metadata:t,taskResult:n})=>{if(n.value){let s=n.value;return {...s,agentId:s.agentId??t.request.agentId,metadata:{...s.metadata,requestIndex:t.index,mode:t.mode}}}let o=n.error??new Error("Unknown error");return {agentId:t.request.agentId,content:o.message,success:false,metadata:{error:o.message,aborted:n.aborted??false,requestIndex:t.index,mode:t.mode}}}),pd=r=>r.filter(e=>!e.success).map(e=>{let t=e.metadata;if(e.error instanceof Error)return {index:t.index,error:e.error};if(e.value&&!e.value.success){let n=String(e.value.metadata?.error??e.value.content??"Agent returned unsuccessful result");return {index:t.index,error:new Error(n)}}return {index:t.index,error:new Error("Unknown failure")}}),gd=(r,e)=>({onTaskComplete:async t=>{vs(e,r,t.success);},onError:async()=>{vs(e,r,false);}}),ws=async(r,e,t={})=>{if(!Array.isArray(r))throw new TypeError("Parallel helpers expect an array of requests");if(r.length===0){let d={total:0,completed:0,successCount:0,failureCount:0,results:[],errors:[],metrics:{totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0}};return t.onComplete?.(d),[]}let n=id(t.concurrency),o=ad(t.timeout),s=ld(t.retryPolicy),i=new at,a=new lt,l=r.map((f,d)=>({id:`${e}:${f.agentId??"anonymous"}:${d}`,metadata:{index:d,mode:e,request:f},run:h=>cd(()=>e==="query"?a.query(f):a.execute(f),s,h.signal)})),u={completed:0,success:0,failure:0,total:r.length},c=await i.run(l,{maxConcurrency:n,timeoutMs:o,evaluateTaskSuccess:f=>f.success,callbacks:gd(u,t)}),p=dd(c),g=pd(c),m=i.getMetrics(),v={total:r.length,completed:r.length,successCount:p.filter(f=>f.success).length,failureCount:p.filter(f=>!f.success).length,results:p,errors:g,metrics:m};return t.onComplete?.(v),p},md=(r,e)=>ws(r,"query",e),fd=(r,e)=>ws(r,"execute",e);Pr();Tr();Cr();Rr();y();y();var It=class{capabilities={required:[]}};y();y();y();var bs=2e3;function _s(r){let e=r.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u2028\u2029]/g,"");return e.length<=bs?e:e.slice(0,bs-11)+" [redacted]"}var kd=10*1024*1024,Rd={b:1,kb:1024,mb:1024*1024,gb:1024*1024*1024};function Mr(r,e){return r===void 0?true:Array.isArray(r)?r.includes(e):r===e}function Cd(r,e){return r===void 0?true:Array.isArray(r)?r.some(t=>e.includes(t)):e.includes(r)}function ks(r){if(typeof r=="number")return r;let e=r.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i);if(!e)return 0;let t=parseFloat(e[1]),n=(e[2]??"b").toLowerCase();return Math.floor(t*(Rd[n]??1))}function Rs(r){return typeof r=="string"}function Cs(r){try{let e=fs$1.statSync(r);return e.size>kd?(process.stderr.write(`[YamlHookPlugin] File too large for line count: ${r} (${e.size} bytes)
74
+ WHERE id = ?`).run(t,s,e);}close(){this.db.close();}rowsToMessages(e){let t=[];for(let n of e){n.prompt&&t.push({id:`${n.id}-user`,text:n.prompt,isAssistant:false,timestamp:new Date(n.started_at).getTime()});let o=Qi(n.result);o&&t.push({id:`${n.id}-assistant`,text:o,isAssistant:true,timestamp:new Date(n.started_at).getTime()});}return t}};var We=class extends Ue{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Be(e?.dbPath);}get conversationProvider(){return this._provider}attach(e){this.unsubStart=e.on("task:start",async t=>{if(!t.threadId)return;let n=t.platform??"cli";try{await this._provider.ensureThread(t.threadId,n,t.workspaceId),await this._provider.saveUserMessage(t.threadId,t.message??"");}catch{}}),this.unsubEnd=e.on("task:end",async t=>{if(!t.result)return;let n=t.metadata?.threadId;if(!n)return;let o=t.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(n,t.result,o);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};h();function fn(r){let e=X__namespace.resolve(r);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,n)=>`${n.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function or(r){let e=fn(r);return crypto$1.createHash("sha256").update(e).digest("hex")}function rd(r){return r?r.settings?.template?.exec:void 0}function nd(){try{let r=new Uint8Array(8);return globalThis.crypto.getRandomValues(r),Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}catch{let{randomBytes:r}=J("crypto");return r(8).toString("hex")}}var Or=class r extends Fe{_agents;_templateEngine;_documentLoader;_layoutLoader;_layoutRenderer;_config;_projectRoot;_workspaceId;_workspaceName;_plugins=[];_tools=new Map;_activeAdapters=new Map;_pendingThreads=new Map;_remoteFactory;_remoteTargets=new Map;constructor(e,t={},n,o,s){super(),this._agents=new Map(e.map(l=>[l.id,l])),this._config=n,this._projectRoot=s??(typeof process<"u"?process.cwd():"/");let i=s??(typeof process<"u"?process.env.CREWX_WORKSPACE??process.cwd():"/");this._workspaceId=or(i),this._workspaceName=X.basename(i);let a=rd(n);this._templateEngine=new $e({execPolicy:t.execPolicy??a}),this._documentLoader=o??new Ce,this._layoutLoader=new He({templatesPath:Se()}),this._layoutRenderer=new qe,this._remoteFactory=t.remoteFactory;}async resolveFileRemoteTarget(e){let t=this.getAgent(e),n=Array.isArray(t?.provider)?t?.provider[0]:t?.provider;if(!n?.startsWith("remote/"))return null;let o=n.slice(7),s=this.getRemoteProviderConfig(o);if(!s?.location?.startsWith("file://"))return null;let i=X.resolve(s.location.replace("file://","")),a=s.external_agent_id??e.replace(/^@/,""),l=this._remoteTargets.get(i);l||(l=(this._remoteFactory??(g=>r.loadYaml(g)))(i),this._remoteTargets.set(i,l),l.catch(()=>this._remoteTargets.delete(i)));let u=await l,c=u.getAgent("@"+a),m=Array.isArray(c?.provider)?c?.provider[0]:c?.provider;if(m?.startsWith("remote/"))throw new Error(`Chained remotes not allowed: "${o}" \u2192 "${m}"`);return {target:u,agentRef:"@"+a}}static async loadBuiltInConfig(e){let{yamlPath:t,dir:n}=Mt(),o;try{o=fs$1.readFileSync(t,"utf-8");}catch(i){throw new Error(`[@crewx/sdk] Cannot read built-in config: ${t}
75
+ ${i.message}`)}let s=ut(o);if(s.documents&&typeof s.documents=="object"){let i={};for(let[a,l]of Object.entries(s.documents))if(l&&typeof l=="object"){let u=l;typeof u.path=="string"&&!X.isAbsolute(u.path)?i[a]={...u,path:X.resolve(n,u.path)}:i[a]=u;}else i[a]=l;return {...s,documents:i}}return s}static mergeCrewxConfig(e,t){let n=new Map;for(let b of e.agents??[])n.set(b.id,b);for(let b of t.agents??[])n.has(b.id)&&console.warn(`[agent-loader] User agent "${b.id}" overrides built-in`),n.set(b.id,b);let o=Array.from(n.values()),s={...e.layouts??{},...t.layouts??{}},i={...e.documents??{},...t.documents??{}},a=e,l=t,u=vs(a.vars,l.vars),c=vs(a.settings,l.settings),m;e.skills&&t.skills&&typeof e.skills=="object"&&typeof t.skills=="object"&&!Array.isArray(e.skills)&&!Array.isArray(t.skills)?m={...e.skills,...t.skills}:m=t.skills??e.skills;let p=[...e.hooks??[],...t.hooks??[]],g=od(a.providers,l.providers),v={...e},f={...t};for(let b of ["agents","layouts","documents","skills","hooks","vars","settings","providers"])delete v[b],delete f[b];let y={...{...v,...f},agents:o,layouts:s,documents:i,skills:m};return p.length>0&&(y.hooks=p),u!==void 0&&(y.vars=u),c!==void 0&&(y.settings=c),g!==void 0&&(y.providers=g),y}static async loadYaml(e,t,n){let o=t?.includeBuiltIns!==false,s,i;if(o){let c=await r.loadBuiltInConfig(n);if(e!==void 0){let m=ct(e);s=r.mergeCrewxConfig(c,m),i=X.dirname(e);}else s=c,i=process.cwd();}else {if(e===void 0)throw new Error("[@crewx/sdk] loadYaml: path is required when includeBuiltIns is false");s=ct(e),i=X.dirname(e);}let a=new Ce(n);await a.load(s.documents,i);let l=s.agents??[];await ws(l,s,t);let u=new r(l,t??{},s,a,i);return await u.use(new We),u}static async fromConfig(e,t,n,o){let s=t?.includeBuiltIns===true,i=e;if(s){let c=await r.loadBuiltInConfig(o);i=r.mergeCrewxConfig(c,e);}let a=new Ce(o);await a.load(i.documents,n??(typeof process<"u"?process.cwd():"/"));let l=i.agents??[];await ws(l,i,t);let u=new r(l,t??{},i,a,n);return await u.use(new We),u}get agents(){return this._agents}get config(){return this._config}get plugins(){return this._plugins}get tools(){return this._tools}get workspaceId(){return this._workspaceId}get workspaceName(){return this._workspaceName}getAgent(e){let t=e.startsWith("@")?e.slice(1):e;return this._agents.get(t)}getRemoteProviderConfig(e){let t=this._config?.providers;return Array.isArray(t)?t.find(o=>o.type==="remote"&&o.id===e):void 0}computeTaskLogPath(e,t){let n=Kt(t);return X.join(this._projectRoot,".crewx","logs",`${n}_${e}.log`)}registerTool(e,t){this._tools.set(e,{name:e,...t});}async use(e){this._plugins.includes(e)||(await e.attach(this),this._plugins.push(e));}handler(e){return nr(this,e)}async registerChannelAdapter(e){let{adapter:t,instanceId:n,config:o}=e;if(this._activeAdapters.has(n))throw new Error(`Adapter instance already registered: ${n}`);let s=new Set(t.manifest.capabilities),i=e.store??Xt(n),a=e.defaultMode??"query",l=t.manifest.platform,u=e.agentRunner??{run:async(g,v,f)=>{let y=await(a==="execute"?this.execute.bind(this):this.query.bind(this))(`@${g}`,v,{threadId:f?.threadId,platform:l});return {output:y.ok?y.data:y.error?.message??""}}},c=e.onInbound??(async g=>{let v=g.routingHints?.agentId??e.defaultAgent;if(!v)return {accepted:false,reason:"no_agent"};let{output:f}=await u.run(v,g.text,{threadId:g.threadId});return {accepted:true,output:f}}),m=Qt({instanceId:n,config:o,capabilities:s,db:i,agentRunner:u,onInbound:c}),p={adapter:t,ctx:m,state:"starting"};this._activeAdapters.set(n,p),this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"starting",timestamp:new Date});try{await t.start(m),p.state="started",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"started",timestamp:new Date});}catch(g){throw p.state="failed",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"failed",error:g instanceof Error?g:new Error(String(g)),timestamp:new Date}),this._activeAdapters.delete(n),g}}async unregisterChannelAdapter(e){let t=this._activeAdapters.get(e);if(t){t.state="stopping",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopping",timestamp:new Date});try{await t.adapter.stop(t.ctx),t.state="stopped",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopped",timestamp:new Date});}catch(n){t.state="failed",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"failed",error:n instanceof Error?n:new Error(String(n)),timestamp:new Date});}finally{this._activeAdapters.delete(e);}}}async stopAllAdapters(e={}){let t=e.timeoutMs??1e4,n=Array.from(this._activeAdapters.keys()),o=await Promise.allSettled(n.map(s=>Promise.race([this.unregisterChannelAdapter(s),new Promise((i,a)=>setTimeout(()=>a(new Error(`Adapter stop timeout: ${s}`)),t))])));for(let s=0;s<o.length;s++)o[s].status==="rejected"&&console.error(`[crewx] adapter stop error (${n[s]}): ${o[s].reason}`);}async close(){await this.stopAllAdapters({timeoutMs:1e4});let e=[...this._remoteTargets.values()];this._remoteTargets.clear(),await Promise.allSettled(e.map(async n=>{try{await(await n).close();}catch(o){console.error(`[crewx] remote target close error: ${o instanceof Error?o.message:String(o)}`);}}));let t=[...this._plugins].reverse();for(let n of t)try{await n.detach(this);}catch(o){console.error(`[crewx] plugin ${n.name} detach error: ${o instanceof Error?o.message:String(o)}`);}this._plugins.length=0;}filterAgents(e){let t=a=>a?a.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,n=t(e.role),o=t(e.team),s=t(e.provider),i=Array.from(this._agents.values());return n&&(i=i.filter(a=>a.role&&n.some(l=>se(a.role.toLowerCase(),l)))),o&&(i=i.filter(a=>a.team&&o.some(l=>se(a.team.toLowerCase(),l)))),s&&(i=i.filter(a=>(Array.isArray(a.provider)?a.provider:[a.provider]).some(u=>s.some(c=>se(u.toLowerCase(),c))))),i}renderAgentPrompt(e){let t=e.startsWith("@")?e.slice(1):e,n=this._agents.get(t);if(!n)throw new de(t,Array.from(this._agents.keys()));return n.inline?.prompt??n.inline?.system_prompt??n.description??`You are an expert ${t}.`}async renderPrompt(e,t){let o={...await this._documentLoader.buildContext(),...t?.documents??{}},s={...t,documents:o};return this._templateEngine.render(e,s)}registerLayout(e,t){this._layoutLoader.registerLayout(e,t);}async renderAgentPromptFull(e,t){let n=e.startsWith("@")?e.slice(1):e,o=this._agents.get(n);if(!o)throw new de(n,Array.from(this._agents.keys()));let s=this._resolveLayoutSpec(o,t?.layout),i=this._extractLayoutId(s),a=this._extractLayoutProps(o,s,t?.layout),l=this._layoutLoader.load(i,a),u=o.inline?.prompt??o.inline?.system_prompt??o.description??`You are an expert ${n}.`,c=await this._documentLoader.buildContext(),m=t?.env??(typeof process<"u"?process.env:{}),p=t?.vars?.security_key??nd(),g={...t?.vars??{},documents:c,env:m,agent:{id:o.id,name:o.name??o.id,role:o.role??"",team:o.team??"",description:o.description??""}},v=await this._templateEngine.render(u,g),f={mode:t?.session?.mode??"query",platform:t?.session?.platform??"cli",options:t?.session?.options??[]},d=o.provider,y=Array.isArray(d)?d:typeof d=="string"&&d.length>0?[d]:[],b=y.join(", ")||(typeof d=="string"?d:""),k=o.options,w=!Array.isArray(k)&&typeof k=="object"&&k!==null?k:void 0,x=Array.isArray(k)?k:void 0,S={};for(let[T,O]of Object.entries(c))S[T]={content:O.content??"",toc:O.toc,summary:O.summary,path:O.path};let R={user_input:t?.vars?.user_input??void 0,agent:{id:o.id,name:o.name??o.id,role:o.role??"",team:o.team??"",description:o.description??"",provider:b,providerList:y,model:o.inline?.model,workingDirectory:o.working_directory??o.workingDirectory??".",inline:{...o.inline??{},prompt:v},specialties:o.specialties??[],capabilities:o.capabilities??[],remote:o.remote??null,optionsByMode:w,optionsArray:x},agentMetadata:{specialties:o.specialties??[],capabilities:o.capabilities??[],description:o.description??""},documents:S,skills:t?.skills??[],session:f,env:m,vars:{security_key:p,...t?.vars??{}},props:{...a??{},...t?.messages&&t.messages.length>0?{showConversationHistory:true}:{}},platform:f.platform,mode:f.mode,messages:t?.messages??[],tools:this._tools.size>0?{list:Array.from(this._tools.values()).map(T=>({name:T.name,description:T.description,parameters:T.parameters})),json:JSON.stringify(Array.from(this._tools.values()).map(T=>({name:T.name,description:T.description,parameters:T.parameters})),null,2),count:this._tools.size}:null,metadata:{}};return this._layoutRenderer.render(l,R)}_filterToolsByMode(e){return e?e.map(t=>this._tools.get(t)).filter(t=>t!==void 0):Array.from(this._tools.values())}_resolveLayoutSpec(e,t){if(t!==void 0)return t;let n=e.inline?.layout;if(n!==void 0)return n;let o=this._config?.layouts?.default;return typeof o=="string"&&o?o:"crewx/default"}_extractLayoutId(e){if(typeof e=="string")return e;if("id"in e)return e.id;let t=`crewx/__inline_${Date.now()}`;return this._layoutLoader.registerLayout(t,e.template),t}_extractLayoutProps(e,t,n){let o=e.inline?.layout,s=o&&typeof o=="object"&&"props"in o?o.props:void 0,i=n&&typeof n=="object"&&"id"in n?n.props:void 0;if(s||i)return {...s??{},...i??{}}}_getConversationProvider(){return this._plugins.find(t=>t.name==="conversation")?.conversationProvider}async _fetchHistoryMessages(e,t,n){if(n&&n.length>0)return n;if(!e)return;let o=this._getConversationProvider();if(o)try{let s=await o.fetchHistory(e,{currentTraceId:t});return s.messages.length===0?void 0:rr(s)}catch{return}}_resolveTimeoutConfig(e){let t=Kr(),n=this._config?.settings??{},o=typeof n.timeoutMs=="number"?n.timeoutMs:void 0,s=typeof n.idleTimeoutMs=="number"?n.idleTimeoutMs:void 0,i=typeof n.killGraceMs=="number"?n.killGraceMs:void 0;return {timeoutMs:e.timeoutMs??o??t.totalMs,idleTimeoutMs:e.idleTimeoutMs??s??t.idleMs,killGraceMs:i??t.killGraceMs}}emitToolEvents(e,t,n,o,s,i,a){try{let l=tr(new Date().toISOString(),o);for(let u of l)u.type==="tool_use"&&u.toolName&&this.emit("tool:observed:before",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:n,tool:{name:u.toolName,rawName:u.toolName,input:u.toolInput?this.tryParseJson(u.toolInput):void 0,toolUseId:u.toolUseId}}),u.type==="tool_result"&&this.emit("tool:observed:after",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:n,tool:{name:u.toolName??"unknown",rawName:u.toolName??"unknown",toolUseId:u.toolUseId,result:u.resultPreview,isError:u.isError}});}catch{}}tryParseJson(e){try{return JSON.parse(e)}catch{return e}}async query(e,t,n){let o=await this.resolveFileRemoteTarget(e);if(o)return o.target.query(o.agentRef,t,n);let s=Date.now(),i=Te("tsk"),a=new Date,l;try{l=pt(e,Array.from(this._agents.values()));}catch(O){if(O instanceof de){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let j=Date.now()-s,I={code:"AGENT_NOT_FOUND",message:O.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:j,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:j}}}throw O}let u=Array.isArray(l.provider)?l.provider[0]??"cli/claude":l.provider,c=n?.provider??u,m=n?.model??l.inline?.model,p;try{p=pe(c);}catch(O){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let j=Date.now()-s,I={code:"PROVIDER_ERROR",message:O.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:j,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:m,durationMs:j}}}let g=await this._fetchHistoryMessages(n?.threadId,i,n?.messages),v;try{v=await this.renderAgentPromptFull(e,{session:{mode:"query",platform:n?.platform},vars:{user_input:t},messages:g});}catch{}let f,d,y,b=m,k=false,w=O=>{k||(k=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",pid:O,model:b,provider:c,codingAgentCommand:f,renderedPrompt:v,metadata:{...n?.metadata??{},provider:c},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},x=l.options,S=Array.isArray(x?.query?.tools)?x.query.tools:void 0,z=this._tools.size>0?this._filterToolsByMode(S):[],R=l.inline?.max_steps,T=this._resolveTimeoutConfig(l);c.startsWith("api/")&&w();try{let O=await p.query(t,{model:m,context:n?.context,systemPrompt:v??l.inline?.system_prompt??l.inline?.prompt,additionalArgs:Array.isArray(x?.query)?x.query:void 0,tools:z.length>0?z:void 0,maxSteps:R,...T,env:{CREWX_AGENT_ID:l.id,CREWX_AGENT_ROLE:l.role??"",CREWX_AGENT_TEAM:l.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:n?.threadId??"",CREWX_PROVIDER:c,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:I=>w(I),onOutput:(I,F)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:I,level:F}),F==="stdout"&&this.emitToolEvents(i,e,c,I,l.id,n?.threadId??"","");},onCommand:I=>{f=I;},onUsage:I=>{d=I;},onExitCode:I=>{y=I;},onModel:I=>{b||(b=I);}});w();let j=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",result:O,durationMs:j,exitCode:y,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:b,metadata:{...n?.metadata??{},...n?.threadId?{threadId:n.threadId}:{}}}),{ok:!0,data:O,meta:{agentId:l.id,provider:c,model:m,durationMs:j}}}catch(O){if(O instanceof exports.ClientToolCallRequiredError){let F=Te("thd");return this._pendingThreads.set(F,{agentRef:l.id,providerStr:c,continuationState:O.continuationState,toolCall:O.toolCall,traceId:i,startMs:s,model:m}),{ok:true,status:"requires_action",data:"",toolCall:O.toolCall,threadId:F,meta:{agentId:l.id,provider:c,model:m,durationMs:Date.now()-s}}}w();let j=Date.now()-s,I={code:"QUERY_FAILED",message:O.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:j,error:I,exitCode:y,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:b,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:m,durationMs:j}}}}async continueQuery(e,t){let n=this._pendingThreads.get(e);if(!n)return {ok:false,data:"",error:{code:"THREAD_NOT_FOUND",message:`No pending thread: ${e}`},meta:{agentId:"",provider:"",durationMs:0}};this._pendingThreads.delete(e);let o=pe(n.providerStr);if(!o.continueWithToolResults)return {ok:false,data:"",error:{code:"UNSUPPORTED",message:"Provider does not support client tool continuation"},meta:{agentId:n.agentRef,provider:n.providerStr,durationMs:0}};let s=t.map(i=>({...i,toolName:n.toolCall.toolCallId===i.toolCallId?n.toolCall.toolName:i.toolCallId}));try{let i=await o.continueWithToolResults(n.continuationState,s),a=Date.now()-n.startMs;return this.emit("task:end",{traceId:n.traceId,timestamp:new Date,agentRef:n.agentRef,mode:"query",result:i,durationMs:a}),{ok:!0,status:"complete",data:i,meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:a}}}catch(i){if(i instanceof exports.ClientToolCallRequiredError)return this._pendingThreads.set(e,{...n,continuationState:i.continuationState,toolCall:i.toolCall}),{ok:true,status:"requires_action",data:"",toolCall:i.toolCall,threadId:e,meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:Date.now()-n.startMs}};let a=Date.now()-n.startMs;return {ok:false,data:"",error:{code:"CONTINUE_FAILED",message:i.message},meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:a}}}}async execute(e,t,n){let o=await this.resolveFileRemoteTarget(e);if(o)return o.target.execute(o.agentRef,t,n);let s=Date.now(),i=Te("tsk"),a=new Date,l;try{l=pt(e,Array.from(this._agents.values()));}catch(O){if(O instanceof de){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let j=Date.now()-s,I={code:"AGENT_NOT_FOUND",message:O.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:j,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:j}}}throw O}let u=Array.isArray(l.provider)?l.provider[0]??"cli/claude":l.provider,c=n?.provider??u,m=n?.model??l.inline?.model,p;try{p=pe(c);}catch(O){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let j=Date.now()-s,I={code:"PROVIDER_ERROR",message:O.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:j,error:I,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:m,durationMs:j}}}let g=await this._fetchHistoryMessages(n?.threadId,i,n?.messages),v;try{v=await this.renderAgentPromptFull(e,{session:{mode:"execute",platform:n?.platform},vars:{user_input:t},messages:g});}catch{}let f,d,y,b=m,k=false,w=O=>{k||(k=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",pid:O,model:b,provider:c,codingAgentCommand:f,renderedPrompt:v,metadata:{...n?.metadata??{},provider:c},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},x=l.options,S=Array.isArray(x?.execute?.tools)?x.execute.tools:void 0,z=this._tools.size>0?this._filterToolsByMode(S):[],R=l.inline?.max_steps,T=this._resolveTimeoutConfig(l);c.startsWith("api/")&&w();try{let O=await p.execute(t,{model:m,context:n?.context,systemPrompt:v??l.inline?.system_prompt??l.inline?.prompt,additionalArgs:Array.isArray(x?.execute)?x.execute:void 0,tools:z.length>0?z:void 0,maxSteps:R,...T,env:{CREWX_AGENT_ID:l.id,CREWX_AGENT_ROLE:l.role??"",CREWX_AGENT_TEAM:l.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:n?.threadId??"",CREWX_PROVIDER:c,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:I=>w(I),onOutput:(I,F)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:I,level:F}),F==="stdout"&&this.emitToolEvents(i,e,c,I,l.id,n?.threadId??"","");},onCommand:I=>{f=I;},onUsage:I=>{d=I;},onExitCode:I=>{y=I;},onModel:I=>{b||(b=I);}});w();let j=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",result:O,durationMs:j,exitCode:y,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:b,metadata:{...n?.metadata??{},...n?.threadId?{threadId:n.threadId}:{}}}),{ok:!0,data:O,meta:{agentId:l.id,provider:c,model:m,durationMs:j}}}catch(O){w();let j=Date.now()-s,I={code:"EXECUTE_FAILED",message:O.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:j,error:I,exitCode:y,inputTokens:d?.inputTokens,outputTokens:d?.outputTokens,cachedInputTokens:d?.cachedInputTokens,costUsd:d?.costUsd,model:b,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:I,meta:{agentId:l.id,provider:c,model:m,durationMs:j}}}}};function vs(r,e){let t=zr(r)?r:void 0,n=zr(e)?e:void 0;if(!(!t&&!n))return {...t??{},...n??{}}}function zr(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function od(r,e){let t=Array.isArray(r)?r:void 0,n=Array.isArray(e)?e:void 0;if(!t&&!n)return;let o=a=>{if(!zr(a))return;let l=a.id;if(typeof l=="string")return `id:${l}`;let u=a.name;if(typeof u=="string")return `name:${u}`},s=new Set;for(let a of n??[]){let l=o(a);l&&s.add(l);}let i=[];for(let a of t??[]){let l=o(a);l&&s.has(l)||i.push(a);}for(let a of n??[])i.push(a);return i}async function ws(r,e,t){if(r.some(o=>(Array.isArray(o.provider)?o.provider:[o.provider]).some(i=>i.startsWith("api/")))){let{registerApiProviders:o}=await Promise.resolve().then(()=>(Pr(),us));o(t?.api);}sd(r,e),id(r,e);}function sd(r,e){if(!r.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(l=>l.startsWith("remote/"))))return;let n=e.providers;if(!Array.isArray(n))return;let{createRemoteProviderFactory:o}=(Sr(),Fr(ds)),s=new Map;for(let i of n)i.type==="remote"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&Ie("remote",o(s,pe));}function id(r,e){if(!r.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(l=>l.startsWith("plugin/"))))return;let n=e.providers;if(!Array.isArray(n))return;let{createPluginProviderFactory:o}=(Ir(),Fr(fs)),s=new Map;for(let i of n)i.type==="plugin"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&Ie("plugin",o(s));}h();var ad="crewx:fs:",Mr=class{prefix;store;constructor(e){this.prefix=e?.prefix??ad,this.store=e?.storage??new Map;}async readFile(e){let t=this.toKey(e),n=this.store.get(t);if(n===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return n}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let t=e.map(i=>i.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),n=t.split("/"),o=[];for(let i of n)i==="."||i===""||(i===".."?o.pop():o.push(i));let s=o.join("/");return t.startsWith("/")?`/${s}`:s}isAbsolute(e){return e.startsWith("/")}setItem(e,t){this.store.set(this.toKey(e),t);}removeItem(e){this.store.delete(this.toKey(e));}keys(){return Array.from(this.store.keys()).filter(e=>e.startsWith(this.prefix)).map(e=>e.slice(this.prefix.length))}toKey(e){return `${this.prefix}${e.replace(/\\/g,"/")}`}};h();function ld(r,e){let t=r.skills?.include;if(t===void 0)return [...e];if(t.length===0)return [];let n=new Set(t);return e.filter(o=>n.has(o))}Re();Tr();Pr();h();var jr=0;function ud(r){let e=Array.from(r.agents.keys());return {name:"delegate_to_agent",description:`Delegate a task to another agent. Available agents: ${e.join(", ")}`,parameters:{type:"object",properties:{agent:{type:"string",description:`Agent ID to delegate to. One of: ${e.join(", ")}`},message:{type:"string",description:"Task description for the target agent"},mode:{type:"string",description:'Execution mode: "query" for questions, "execute" for actions. Default: query'}},required:["agent","message"]},execute:async t=>{if(jr>=3)return "Error: Maximum delegation depth (3) reached. Cannot delegate further.";let n=t.agent,o=t.message,s=t.mode??"query";if(!e.includes(n))return `Error: Unknown agent "${n}". Available: ${e.join(", ")}`;jr++;try{if(s==="execute"){let a=await r.execute(n,o);return a.ok?a.data:`Error: ${a.error?.message??"Unknown error"}`}let i=await r.query(n,o);return i.ok?i.data:`Error: ${i.error?.message??"Unknown error"}`}finally{jr--;}}}}h();var bs=typeof process<"u"?process.env:{};function cd(){return bs.CREWX_CLI||"npx crewx"}function dd(){return bs.CREWX_WORKSPACE||(typeof process<"u"?process.cwd():"/")}h();var pd=/^[a-zA-Z0-9._-]+$/,Nr=class{constructor(e){this.storage=e;}storage;listBoxes(e){this.validateId(e);let n=this.storage.listBoxes(e).map(o=>this.toBoxResponse(o));return {boxes:n,total:n.length}}getBox(e,t){this.validateId(e),this.validateId(t);let n=this.storage.findBox(e,t);return n?this.toBoxResponse(n):null}createBox(e,t){this.validateId(e);let n=this.generateBoxId(),o=new Date().toISOString(),s=this.storage.insertBox(e,{id:n,seq:t.seq,firstTaskId:t.firstTaskId,midTaskId:t.midTaskId,lastTaskId:t.lastTaskId,taskCount:t.taskCount,summary:t.summary??null,sourceTokens:t.sourceTokens,summaryTokens:t.summaryTokens??null,createdAt:o});return this.toBoxResponse(s)}toBoxResponse(e){return {id:e.id,threadId:e.thread_id,seq:e.seq,firstTaskId:e.first_task_id,lastTaskId:e.last_task_id,taskCount:e.task_count,sourceTokens:e.source_tokens,summaryTokens:e.summary_tokens,summary:e.summary,previewFirst:this.storage.getTaskPreview(e.first_task_id,200),previewMid:this.storage.getTaskPreview(e.mid_task_id,200),previewLast:this.storage.getTaskPreview(e.last_task_id,200),createdAt:e.created_at}}validateId(e){if(!pd.test(e))throw new Error(`Invalid ID format: ${e}`)}generateBoxId(){return Te("box")}};h();function gd(r,e,t,n,o){let{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}=n,l=s*i,u=s*a,c=l+u,m=e.getThreadMessages(r),p=[],g=0,v=false,f=[];for(let b=0;b<m.length;b+=2){let k=m[b],w=m[b+1],x=k?.content||"",S=w?.content||"",z=o.countTokens(x+S),R=[];k&&R.push(k),w&&R.push(w),f.push({messages:R,tokens:z});}for(let b=f.length-1;b>=0;b--){let k=f[b];if(g+k.tokens>l){v=true;break}g+=k.tokens,p.unshift(...k.messages);}let d=[],y=0;if(v&&u>0)try{let{boxes:b}=t.listBoxes(r);for(let k=b.length-1;k>=0;k--){let w=b[k],x=w.summaryTokens??w.sourceTokens;if(y+x>u)break;y+=x,d.unshift({boxId:w.id,seq:w.seq,taskCount:w.taskCount,sourceTokens:w.sourceTokens,summary:w.summary,previewFirst:w.previewFirst,previewMid:w.previewMid,previewLast:w.previewLast,createdAt:w.createdAt});}}catch(b){if(b instanceof Error&&!/not found/i.test(b.message))throw b}return {hot:p,warm:d,hotTokens:g,warmTokens:y,hotOverflow:v,totalBudget:c,config:{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}}}Nt();h();var St=class extends Error{constructor(t,n){super(`Task ${t} timed out after ${n}ms`);this.taskId=t;this.timeoutMs=n;this.name="ParallelRunnerTimeoutError";}taskId;timeoutMs},at=class{constructor(e={}){this.defaults=e;}defaults;metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0};async run(e,t={}){if(!Array.isArray(e))throw new TypeError("ParallelRunner.run expects an array of tasks");if(e.length===0)return this.metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0},[];let n=this.mergeOptions(t),o=Math.max(1,n.maxConcurrency??5),s=n.timeoutMs,i=n.failFast??false,a=n.callbacks,l=n.evaluateTaskSuccess??(()=>true),u=[],c=0,m=0,p=0,g=false,v=0,f=perf_hooks.performance.now(),d=async R=>{a?.onTaskStart&&await a.onTaskStart(R),p+=1;let T=new AbortController,O={signal:T.signal},j,I;typeof s=="number"&&Number.isFinite(s)&&s>0&&(I=new Promise((te,ne)=>{j=setTimeout(()=>{let U=new St(R.id,s);T.abort(U),ne(U);},s);}));let F=perf_hooks.performance.now(),L=R.run(O),be=I?Promise.race([L,I]):L;try{let te=await be,ne=perf_hooks.performance.now(),U=ne-F,Y=l(te,R),V={taskId:R.id,success:Y,value:te,durationMs:U,startedAt:F,finishedAt:ne,metadata:R.metadata,aborted:!1};u.push(V),Y?c+=1:m+=1,a?.onTaskComplete&&await a.onTaskComplete(V),i&&!Y&&(g=!0);}catch(te){let ne=perf_hooks.performance.now(),U=ne-F,Y=te instanceof Error?te:new Error(String(te)),V={taskId:R.id,success:false,error:Y,durationMs:U,startedAt:F,finishedAt:ne,metadata:R.metadata,aborted:T.signal.aborted};u.push(V),m+=1,a?.onError&&await a.onError(R,Y,U),i&&(g=true);}finally{j&&clearTimeout(j),I&&L.catch(()=>{});}},y=async()=>{for(;!g;){let R=v;if(R>=e.length)break;v+=1;let T=e[R];if(!T||(await d(T),g))break}},b=Math.min(o,e.length),k=[];for(let R=0;R<b;R++)k.push(y());await Promise.all(k);let x=perf_hooks.performance.now()-f,S=u.length?u.reduce((R,T)=>R+T.durationMs,0)/u.length:0,z=x>0?u.length/(x/1e3):u.length;return this.metrics={totalTasks:e.length,startedTasks:p,completedTasks:u.length,successCount:c,failureCount:m,totalDurationMs:x,averageDurationMs:S,throughput:z},u}getMetrics(){return this.metrics}mergeOptions(e){return {maxConcurrency:e.maxConcurrency??this.defaults.maxConcurrency,timeoutMs:e.timeoutMs??this.defaults.timeoutMs,failFast:e.failFast??this.defaults.failFast,evaluateTaskSuccess:e.evaluateTaskSuccess??this.defaults.evaluateTaskSuccess,callbacks:this.mergeCallbacks(this.defaults.callbacks,e.callbacks)}}mergeCallbacks(e,t){if(!(!e&&!t))return {onTaskStart:async n=>{e?.onTaskStart&&await e.onTaskStart(n),t?.onTaskStart&&await t.onTaskStart(n);},onTaskComplete:async n=>{e?.onTaskComplete&&await e.onTaskComplete(n),t?.onTaskComplete&&await t.onTaskComplete(n);},onError:async(n,o,s)=>{e?.onError&&await e.onError(n,o,s),t?.onError&&await t.onError(n,o,s);}}}};h();h();var lt=class{async query(e){throw new Error("AgentRuntime.query is not implemented. Provide a subclass or mock AgentRuntime.prototype.query.")}async execute(e){throw new Error("AgentRuntime.execute is not implemented. Provide a subclass or mock AgentRuntime.prototype.execute.")}};var _s=3,xs=3e4,ks=500,md=r=>{if(typeof r!="number"||Number.isNaN(r)||!Number.isFinite(r))return _s;let e=Math.floor(r);return e>0?e:_s},fd=r=>r===void 0||typeof r!="number"||Number.isNaN(r)||r<=0?xs:r,hd=r=>{if(!r)return {maxRetries:0,retryDelay:ks};let e=Number.isInteger(r.maxRetries)&&r.maxRetries>=0?r.maxRetries:0,t=typeof r.retryDelay=="number"&&r.retryDelay>=0?r.retryDelay:ks;return {maxRetries:e,retryDelay:t}},Dr=r=>{let e=r.reason;return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("Parallel operation aborted")},yd=(r,e)=>r<=0?Promise.resolve():new Promise((t,n)=>{let o=setTimeout(()=>{e.removeEventListener("abort",s),t();},r),s=()=>{clearTimeout(o),n(Dr(e));};if(e.aborted){s();return}e.addEventListener("abort",s,{once:true});}),vd=async(r,e,t)=>{let n,o;for(let s=0;s<=e.maxRetries;s++){if(t.aborted)throw Dr(t);try{let i=await r();if(n=i,i.success||s===e.maxRetries)return i}catch(i){if(o=i,t.aborted)throw Dr(t);if(s===e.maxRetries)throw i instanceof Error?i:new Error(String(i))}s<e.maxRetries&&await yd(e.retryDelay,t);}if(n)return n;throw o?o instanceof Error?o:new Error(String(o)):new Error("Parallel helper encountered an unexpected state")},Rs=(r,e,t)=>{e.completed+=1,t?e.success+=1:e.failure+=1;try{r.onProgress?.(e.completed,e.total);}catch(n){process.env.NODE_ENV!=="production"&&console.warn("Parallel helper onProgress callback threw an error:",n);}},wd=r=>r.map(t=>({metadata:t.metadata,taskResult:t})).slice().sort((t,n)=>t.metadata.index-n.metadata.index).map(({metadata:t,taskResult:n})=>{if(n.value){let s=n.value;return {...s,agentId:s.agentId??t.request.agentId,metadata:{...s.metadata,requestIndex:t.index,mode:t.mode}}}let o=n.error??new Error("Unknown error");return {agentId:t.request.agentId,content:o.message,success:false,metadata:{error:o.message,aborted:n.aborted??false,requestIndex:t.index,mode:t.mode}}}),bd=r=>r.filter(e=>!e.success).map(e=>{let t=e.metadata;if(e.error instanceof Error)return {index:t.index,error:e.error};if(e.value&&!e.value.success){let n=String(e.value.metadata?.error??e.value.content??"Agent returned unsuccessful result");return {index:t.index,error:new Error(n)}}return {index:t.index,error:new Error("Unknown failure")}}),_d=(r,e)=>({onTaskComplete:async t=>{Rs(e,r,t.success);},onError:async()=>{Rs(e,r,false);}}),Cs=async(r,e,t={})=>{if(!Array.isArray(r))throw new TypeError("Parallel helpers expect an array of requests");if(r.length===0){let d={total:0,completed:0,successCount:0,failureCount:0,results:[],errors:[],metrics:{totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0}};return t.onComplete?.(d),[]}let n=md(t.concurrency),o=fd(t.timeout),s=hd(t.retryPolicy),i=new at,a=new lt,l=r.map((f,d)=>({id:`${e}:${f.agentId??"anonymous"}:${d}`,metadata:{index:d,mode:e,request:f},run:y=>vd(()=>e==="query"?a.query(f):a.execute(f),s,y.signal)})),u={completed:0,success:0,failure:0,total:r.length},c=await i.run(l,{maxConcurrency:n,timeoutMs:o,evaluateTaskSuccess:f=>f.success,callbacks:_d(u,t)}),m=wd(c),p=bd(c),g=i.getMetrics(),v={total:r.length,completed:r.length,successCount:m.filter(f=>f.success).length,failureCount:m.filter(f=>!f.success).length,results:m,errors:p,metrics:g};return t.onComplete?.(v),m},xd=(r,e)=>Cs(r,"query",e),kd=(r,e)=>Cs(r,"execute",e);Ir();Sr();Ar();Er();h();h();var It=class{capabilities={required:[]}};h();h();h();var Ts=2e3;function Ps(r){let e=r.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u2028\u2029]/g,"");return e.length<=Ts?e:e.slice(0,Ts-11)+" [redacted]"}var Id=10*1024*1024,Od={b:1,kb:1024,mb:1024*1024,gb:1024*1024*1024};function $r(r,e){return r===void 0?true:Array.isArray(r)?r.includes(e):r===e}function zd(r,e){return r===void 0?true:Array.isArray(r)?r.some(t=>e.includes(t)):e.includes(r)}function As(r){if(typeof r=="number")return r;let e=r.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i);if(!e)return 0;let t=parseFloat(e[1]),n=(e[2]??"b").toLowerCase();return Math.floor(t*(Od[n]??1))}function Ss(r){return typeof r=="string"}function Is(r){try{let e=fs$1.statSync(r);return e.size>Id?(process.stderr.write(`[YamlHookPlugin] File too large for line count: ${r} (${e.size} bytes)
75
76
  `),null):fs$1.readFileSync(r,"utf8").split(`
76
- `).length}catch{return null}}function Ts(r){try{return fs$1.statSync(r).size}catch{return null}}function Td(r,e,t){if(!r)return true;let n=e,o=n?.path??n?.file_path??n?.filePath??n?.filename;if(typeof o!="string")return false;if(se(o,r))return true;if(t&&o.startsWith("/")){let{relative:s,isAbsolute:i}=U("path");if(i(o)){let a=s(t,o);if(a&&!a.startsWith("..")&&se(a,r))return true}}return false}function Pd(r,e){return r?JSON.stringify(e).includes(r):true}function Ed(r,e){if(!r)return true;try{let t=new RegExp(r),n=JSON.stringify(e);return t.test(n)}catch{return false}}function Ad(r,e){if(!r)return true;try{let t=new RegExp(r),n=JSON.stringify(e);return t.test(n)}catch{return false}}function Sd(r,e){if(r.pathSizeMin===void 0&&r.pathSizeMax===void 0)return true;let t=e,n=t?.path??t?.file_path??t?.filePath??t?.filename;if(typeof n!="string")return false;if(r.pathSizeMin!==void 0)if(Rs(r.pathSizeMin)){let o=Ts(n);if(o===null||o<ks(r.pathSizeMin))return false}else {let o=Cs(n);if(o===null||o<r.pathSizeMin)return false}if(r.pathSizeMax!==void 0)if(Rs(r.pathSizeMax)){let o=Ts(n);if(o===null||o>ks(r.pathSizeMax))return false}else {let o=Cs(n);if(o===null||o>r.pathSizeMax)return false}return true}function Id(r){let e=[],t=[];for(let n=0;n<r.length;n++){let o=r[n];if(!o||typeof o!="object"){t.push(`Hook at index ${n}: not an object, skipping`);continue}let s=o;if(typeof s.name!="string"||!s.name){t.push(`Hook at index ${n}: missing or invalid "name", skipping`);continue}let i=s.guide&&typeof s.guide=="object",a=s.deny&&typeof s.deny=="object",l=typeof s.plugin=="string";if(!i&&!a&&!l){t.push(`Hook "${s.name}": missing guide/deny/plugin, skipping`);continue}if(i&&typeof s.guide.say!="string"){t.push(`Hook "${s.name}": guide.say is required and must be string, skipping`);continue}if(a&&typeof s.deny.reason!="string"){t.push(`Hook "${s.name}": deny.reason is required and must be string, skipping`);continue}e.push(s);}return {valid:e,warnings:t}}var Nr=class extends It{name="@crewx/yaml-hook-plugin";version="0.1.0";capabilities={required:["inject"]};hooks;agentMap;constructor(e){super(),this.hooks=e.hooks,this.agentMap=new Map((e.agents??[]).map(t=>[t.id,t]));}async run(e){let t=[],n=process.env.CREWX_TASK_LOG_PATH,o=process.env.CREWX_HOOK_LOG_VERBOSE==="1";for(let s of this.hooks)if(this.matchEntryLevel(s,e)&&s.guide){if(!this.matchRuleLevel(s.guide,e)){o&&n&&this.appendHookLog(n,{rule:s.name,action:"pass",once:s.guide.once??false,ctx:e,matched:false});continue}s.guide.once&&this.hasFired(e.sessionId,s.name)||(s.guide.once&&this.markFired(e.sessionId,s.name),t.push(s.guide.say),n&&this.appendHookLog(n,{rule:s.name,action:"inject",once:s.guide.once??false,ctx:e,matched:true,message:s.guide.say}));}return t.length?e.inject(t.join(`
77
+ `).length}catch{return null}}function Os(r){try{return fs$1.statSync(r).size}catch{return null}}function Md(r,e,t){if(!r)return true;let n=e,o=n?.path??n?.file_path??n?.filePath??n?.filename;if(typeof o!="string")return false;if(se(o,r))return true;if(t&&o.startsWith("/")){let{relative:s,isAbsolute:i}=J("path");if(i(o)){let a=s(t,o);if(a&&!a.startsWith("..")&&se(a,r))return true}}return false}function jd(r,e){return r?JSON.stringify(e).includes(r):true}function Nd(r,e){if(!r)return true;try{let t=new RegExp(r),n=JSON.stringify(e);return t.test(n)}catch{return false}}function Dd(r,e){if(!r)return true;try{let t=new RegExp(r),n=JSON.stringify(e);return t.test(n)}catch{return false}}function $d(r,e){if(r.pathSizeMin===void 0&&r.pathSizeMax===void 0)return true;let t=e,n=t?.path??t?.file_path??t?.filePath??t?.filename;if(typeof n!="string")return false;if(r.pathSizeMin!==void 0)if(Ss(r.pathSizeMin)){let o=Os(n);if(o===null||o<As(r.pathSizeMin))return false}else {let o=Is(n);if(o===null||o<r.pathSizeMin)return false}if(r.pathSizeMax!==void 0)if(Ss(r.pathSizeMax)){let o=Os(n);if(o===null||o>As(r.pathSizeMax))return false}else {let o=Is(n);if(o===null||o>r.pathSizeMax)return false}return true}function Hd(r){let e=[],t=[];for(let n=0;n<r.length;n++){let o=r[n];if(!o||typeof o!="object"){t.push(`Hook at index ${n}: not an object, skipping`);continue}let s=o;if(typeof s.name!="string"||!s.name){t.push(`Hook at index ${n}: missing or invalid "name", skipping`);continue}let i=s.guide&&typeof s.guide=="object",a=s.deny&&typeof s.deny=="object",l=typeof s.plugin=="string";if(!i&&!a&&!l){t.push(`Hook "${s.name}": missing guide/deny/plugin, skipping`);continue}if(i&&typeof s.guide.say!="string"){t.push(`Hook "${s.name}": guide.say is required and must be string, skipping`);continue}if(a&&typeof s.deny.reason!="string"){t.push(`Hook "${s.name}": deny.reason is required and must be string, skipping`);continue}e.push(s);}return {valid:e,warnings:t}}var Lr=class extends It{name="@crewx/yaml-hook-plugin";version="0.1.0";capabilities={required:["inject"]};hooks;agentMap;constructor(e){super(),this.hooks=e.hooks,this.agentMap=new Map((e.agents??[]).map(t=>[t.id,t]));}async run(e){let t=[],n=process.env.CREWX_TASK_LOG_PATH,o=process.env.CREWX_HOOK_LOG_VERBOSE==="1";for(let s of this.hooks)if(this.matchEntryLevel(s,e)&&s.guide){if(!this.matchRuleLevel(s.guide,e)){o&&n&&this.appendHookLog(n,{rule:s.name,action:"pass",once:s.guide.once??false,ctx:e,matched:false});continue}s.guide.once&&this.hasFired(e.sessionId,s.name)||(s.guide.once&&this.markFired(e.sessionId,s.name),t.push(s.guide.say),n&&this.appendHookLog(n,{rule:s.name,action:"inject",once:s.guide.once??false,ctx:e,matched:true,message:s.guide.say}));}return t.length?e.inject(t.join(`
77
78
 
78
- `)):e.pass()}appendHookLog(e,t){try{let n={rule:t.rule,action:t.action,once:t.once,sessionId:t.ctx.sessionId,provider:t.ctx.provider,agent:t.ctx.agent.id,toolName:t.ctx.tool.name,rawToolName:t.ctx.tool.rawName};t.message&&(n.chars=t.message.length,process.env.CREWX_HOOK_LOG_VERBOSE==="1"&&(n.message=_s(t.message).slice(0,500)));let o=`[${new Date().toISOString()}] HOOK: ${JSON.stringify(n)}
79
- `;fs$1.appendFileSync(e,o,{encoding:"utf8",mode:384});}catch{}}matchEntryLevel(e,t){if(e.provider!==void 0){let n=t.provider.replace(/^cli\//,"");if(!Mr(e.provider,n))return false}if(e.team!==void 0){let o=this.agentMap.get(t.agent.id)?.team??t.agent.team;if(!Mr(e.team,o))return false}if(e.role!==void 0){let o=this.agentMap.get(t.agent.id)?.role??t.agent.role;if(!Mr(e.role,o))return false}if(e.tag!==void 0){let o=this.agentMap.get(t.agent.id)?.tags??[];if(!Cd(e.tag,o))return false}return !(e.agents!==void 0&&!e.agents.includes(t.agent.id))}matchRuleLevel(e,t){return !(e.when!==void 0&&e.when.length>0&&!e.when.includes(t.tool.name)&&!e.when.includes(t.tool.rawName)||!Pd(e.pattern,t.tool.input)||!Ed(e.regex,t.tool.input)||!Td(e.pathPattern,t.tool.input,t.cwd)||!Sd(e,t.tool.input)||!Ad(e.whenInputRegex,t.tool.input))}hasFired(e,t){try{let n=this.firedFilePath(e);if(!fs$1.existsSync(n))return !1;let o=JSON.parse(fs$1.readFileSync(n,"utf8"));return Array.isArray(o.fired)&&o.fired.includes(t)}catch{return false}}markFired(e,t){try{let n=this.firedFilePath(e);fs$1.mkdirSync(X.dirname(n),{recursive:!0,mode:448});let o=fs$1.existsSync(n)?JSON.parse(fs$1.readFileSync(n,"utf8")):{fired:[]};Array.isArray(o.fired)||(o.fired=[]),o.fired.includes(t)||(o.fired.push(t),fs$1.writeFileSync(n,JSON.stringify(o),{mode:384}));}catch(n){process.stderr.write(`[YamlHookPlugin] once state write failed: ${n}
80
- `);}}firedFilePath(e){let t=crypto$1.createHash("sha1").update(e).digest("hex");return X.join(os$1.homedir(),".crewx","sessions",t,"fired-rules.json")}};y();y();y();function Od(r){let e=r.messages.map(t=>({id:t.id,role:t.isAssistant?"assistant":"user",content:t.text,timestamp:new Date(t.timestamp).toISOString(),metadata:t.metadata??null}));return {getThreadMessages(t){return e}}}y();var $r=class extends Error{code;kind;retryAfterMs;constructor(e,t,n){super(`AdapterError: ${e}`),this.name="AdapterError",this.code=e,this.kind=t,this.retryAfterMs=n;}};y();function zd(r){return r}function Md(r){return {name:r.name,async attach(e){let t=await r.configFactory(e),o=e.registerChannelAdapter,s=r.instanceId??r.name;o&&await o({adapter:r.adapter,instanceId:s,config:t}),r.onAttach&&await r.onAttach(e);},async detach(e){let n=e.unregisterChannelAdapter;n&&await n(r.instanceId??r.name),r.onDetach&&await r.onDetach(e);}}}ft();exports.AdapterError=$r;exports.AgentNotFoundError=de;exports.AgentRuntime=lt;exports.BrowserFsAdapter=Sr;exports.ConfigLoadError=xe;exports.Crewx=Er;exports.CrewxPlugin=Ue;exports.DocumentLoader=Ce;exports.LayoutLoadError=Q;exports.LayoutLoader=He;exports.LayoutRenderer=qe;exports.NodeFsAdapter=ht;exports.ParallelRunner=at;exports.ParallelRunnerTimeoutError=St;exports.PropsValidationError=ge;exports.PropsValidator=Le;exports.SdkBoxService=Or;exports.SqliteConversationProvider=Be;exports.TemplateEngine=De;exports.TypedEventEmitter=Fe;exports.YamlHookPlugin=Nr;exports.buildContext=sd;exports.createAdapterContext=Kt;exports.createDelegateTool=td;exports.createHandler=Zt;exports.createPluginProviderFactory=ls;exports.createProvider=pe;exports.createRemoteProviderFactory=os;exports.createScopedAdapterStore=Jt;exports.defaultFsAdapter=Ut;exports.defineChannelAdapter=zd;exports.defineChannelAdapterPlugin=Md;exports.escapeHandlebarsHelper=Lt;exports.formatFileSizeHelper=qt;exports.formatTimestamp=Wt;exports.formatTimestampHelper=Ft;exports.generateFingerprint=ki;exports.generateId=Te;exports.getSyncWindowStore=Ti;exports.hashWorkspaceId=er;exports.lengthHelper=Ht;exports.loadYamlFile=ct;exports.materializeWindowsSpawnProgram=Ne;exports.normalizeWorkspacePath=un;exports.parseStdoutEvent=Yt;exports.parseUsage=jt;exports.parseYamlContent=ut;exports.registerApiProviders=rs;exports.registerProviderFactory=Ie;exports.resolveAgent=pt;exports.resolveCrewxCli=rd;exports.resolveCrewxWorkspace=nd;exports.resolveDefaultAgentsYaml=Mt;exports.resolveTemplatesPath=Se;exports.resolveWindowsExecutablePath=qr;exports.resolveWindowsSpawnProgram=je;exports.runExecutesParallel=fd;exports.runInSyncWindow=Pi;exports.runQueriesParallel=md;exports.setAuditVerbose=ci;exports.toTaskReader=Od;exports.toTemplateMessages=Qt;exports.truncateHelper=Dt;exports.validateHooksSchema=Id;
79
+ `)):e.pass()}appendHookLog(e,t){try{let n={rule:t.rule,action:t.action,once:t.once,sessionId:t.ctx.sessionId,provider:t.ctx.provider,agent:t.ctx.agent.id,toolName:t.ctx.tool.name,rawToolName:t.ctx.tool.rawName};t.message&&(n.chars=t.message.length,process.env.CREWX_HOOK_LOG_VERBOSE==="1"&&(n.message=Ps(t.message).slice(0,500)));let o=`[${new Date().toISOString()}] HOOK: ${JSON.stringify(n)}
80
+ `;fs$1.appendFileSync(e,o,{encoding:"utf8",mode:384});}catch{}}matchEntryLevel(e,t){if(e.provider!==void 0){let n=t.provider.replace(/^cli\//,"");if(!$r(e.provider,n))return false}if(e.team!==void 0){let o=this.agentMap.get(t.agent.id)?.team??t.agent.team;if(!$r(e.team,o))return false}if(e.role!==void 0){let o=this.agentMap.get(t.agent.id)?.role??t.agent.role;if(!$r(e.role,o))return false}if(e.tag!==void 0){let o=this.agentMap.get(t.agent.id)?.tags??[];if(!zd(e.tag,o))return false}return !(e.agents!==void 0&&!e.agents.includes(t.agent.id))}matchRuleLevel(e,t){return !(e.when!==void 0&&e.when.length>0&&!e.when.includes(t.tool.name)&&!e.when.includes(t.tool.rawName)||!jd(e.pattern,t.tool.input)||!Nd(e.regex,t.tool.input)||!Md(e.pathPattern,t.tool.input,t.cwd)||!$d(e,t.tool.input)||!Dd(e.whenInputRegex,t.tool.input))}hasFired(e,t){try{let n=this.firedFilePath(e);if(!fs$1.existsSync(n))return !1;let o=JSON.parse(fs$1.readFileSync(n,"utf8"));return Array.isArray(o.fired)&&o.fired.includes(t)}catch{return false}}markFired(e,t){try{let n=this.firedFilePath(e);fs$1.mkdirSync(X.dirname(n),{recursive:!0,mode:448});let o=fs$1.existsSync(n)?JSON.parse(fs$1.readFileSync(n,"utf8")):{fired:[]};Array.isArray(o.fired)||(o.fired=[]),o.fired.includes(t)||(o.fired.push(t),fs$1.writeFileSync(n,JSON.stringify(o),{mode:384}));}catch(n){process.stderr.write(`[YamlHookPlugin] once state write failed: ${n}
81
+ `);}}firedFilePath(e){let t=crypto$1.createHash("sha1").update(e).digest("hex");return X.join(os.homedir(),".crewx","sessions",t,"fired-rules.json")}};h();h();h();function Ld(r){let e=r.messages.map(t=>({id:t.id,role:t.isAssistant?"assistant":"user",content:t.text,timestamp:new Date(t.timestamp).toISOString(),metadata:t.metadata??null}));return {getThreadMessages(t){return e}}}h();var qr=class extends Error{code;kind;retryAfterMs;constructor(e,t,n){super(`AdapterError: ${e}`),this.name="AdapterError",this.code=e,this.kind=t,this.retryAfterMs=n;}};h();function qd(r){return r}function Fd(r){return {name:r.name,async attach(e){let t=await r.configFactory(e),o=e.registerChannelAdapter,s=r.instanceId??r.name;o&&await o({adapter:r.adapter,instanceId:s,config:t}),r.onAttach&&await r.onAttach(e);},async detach(e){let n=e.unregisterChannelAdapter;n&&await n(r.instanceId??r.name),r.onDetach&&await r.onDetach(e);}}}ft();exports.AdapterError=qr;exports.AgentNotFoundError=de;exports.AgentRuntime=lt;exports.AgentSkillsSchema=Ur;exports.BrowserFsAdapter=Mr;exports.ConfigLoadError=xe;exports.Crewx=Or;exports.CrewxPlugin=Ue;exports.DocumentLoader=Ce;exports.LayoutLoadError=Q;exports.LayoutLoader=He;exports.LayoutRenderer=qe;exports.NodeFsAdapter=ht;exports.ParallelRunner=at;exports.ParallelRunnerTimeoutError=St;exports.PropsValidationError=ge;exports.PropsValidator=Le;exports.SdkBoxService=Nr;exports.SqliteConversationProvider=Be;exports.TemplateEngine=$e;exports.TypedEventEmitter=Fe;exports.YamlHookPlugin=Lr;exports.buildContext=gd;exports.createAdapterContext=Qt;exports.createDelegateTool=ud;exports.createHandler=nr;exports.createPluginProviderFactory=ms;exports.createProvider=pe;exports.createRemoteProviderFactory=cs;exports.createScopedAdapterStore=Xt;exports.defaultFsAdapter=Vt;exports.defineChannelAdapter=qd;exports.defineChannelAdapterPlugin=Fd;exports.escapeHandlebarsHelper=Bt;exports.formatFileSizeHelper=Wt;exports.formatTimestamp=Kt;exports.formatTimestampHelper=Jt;exports.generateFingerprint=Si;exports.generateId=Te;exports.getSyncWindowStore=zi;exports.hashWorkspaceId=or;exports.lengthHelper=Ut;exports.loadYamlFile=ct;exports.materializeWindowsSpawnProgram=Ne;exports.normalizeWorkspacePath=fn;exports.parseStdoutEvent=tr;exports.parseUsage=jt;exports.parseYamlContent=ut;exports.registerApiProviders=ls;exports.registerProviderFactory=Ie;exports.resolveAgent=pt;exports.resolveAgentSkills=ld;exports.resolveCrewxCli=cd;exports.resolveCrewxWorkspace=dd;exports.resolveDefaultAgentsYaml=Mt;exports.resolveTemplatesPath=Se;exports.resolveWindowsExecutablePath=Jr;exports.resolveWindowsSpawnProgram=je;exports.runExecutesParallel=kd;exports.runInSyncWindow=Mi;exports.runQueriesParallel=xd;exports.setAuditVerbose=yi;exports.toTaskReader=Ld;exports.toTemplateMessages=rr;exports.truncateHelper=Ft;exports.validateHooksSchema=Hd;